【发布时间】:2016-04-21 19:36:15
【问题描述】:
我需要一些电子邮件表单,我正在尝试这个:
views.py
def send_email(request):
if request.method != 'POST':
form = EmailForm()
return render_to_response('mail_form.html', {'email_form': form})
form = EmailForm(request.POST, request.FILES)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
email = form.cleaned_data['email']
attach = request.FILES['attach']
try:
mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
mail.attach(attach.name, attach.read(), attach.content_type)
mail.send()
return render(request, 'mail_form.html', {'message': 'Sent email to %s'%email})
except:
return render(request, 'mail_form.html', {'message': 'Either the attachment is too big or corrupt'})
return render(request, 'mail_form.html', {'message': 'Unable to send email. Please try again later'})
forms.py
class EmailForm(forms.Form):
email = forms.EmailField()
subject = forms.CharField(max_length=100)
attach = forms.Field(widget=forms.FileInput)
message = forms.CharField(widget = forms.Textarea)
mail_form.html
...
{{message}}
<form method="post" action="">
{% csrf_token %}
{{ email_form.as_p }}
<input type ="submit" name = "send" value = "Send"/>
</form>
...
但我经常收到错误 403。我尝试了网络上的不同解决方案,但没有任何帮助。我做错了什么?我知道views.py中的csrf有问题,但不明白具体问题出在哪里。
【问题讨论】:
-
您的缩进不正确。修复它。
-
@7stud 已修复,谢谢
-
您是否启用了 CSRF 中间件
django.middleware.csrf.CsrfViewMiddleware? -
你使用的是什么版本的 django?
-
Pythonista 的答案似乎是正确的,至少我不再得到 403
标签: python django django-views django-csrf