显示“此字段必填"的Django Contact Form附件.我究竟做错了什么? [英] Django Contact Form Attachment showing 'This field is required.' What am I doing Wrong?
本文介绍了显示“此字段必填"的Django Contact Form附件.我究竟做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Views.py
from django.conf import settings
from django.core.mail import EmailMessage,send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
name = form.cleaned_data['name']
phone = form.cleaned_data['phone']
image1 = request.FILES['image1']
full_message = str([from_email,name.upper(), phone, message])
try:
email = EmailMessage(subject.upper(),full_message,from_email+'<sender@gmail.com>',['pratirup8@gmail.com'],headers = {'Reply-To': from_email })
email.attach(image1.name, image1.read(), image1.content_type)
email.send()
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
Forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(required=True)
phone = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True )
如果我发送的邮件中没有附件,则它可以正常工作,但是当我添加附件文件时,它会显示此字段为必填字段".在网页此图片是问题的屏幕截图,我想知道自己在做什么错误,如何发送和发送带有附件的邮件
If I send the mail with out attachment its working but when i add an attachment file it shows "This field is required." in the webpagethis image is a screenshot of the problem i want to know what am doing wrong and how can i send and mail with the attachment
推荐答案
您还需要将FILES传递到表单中,因为它具有文件字段:
You need to pass FILES into the form as well, since it has a file field:
form = ContactForm(request.POST, request.FILES)
在文档来上传文件.
这篇关于显示“此字段必填"的Django Contact Form附件.我究竟做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文