问题
I am trying to learn django by working through "The Django Book", and I'm having a problem with CSRF protection. I've found lots of suggestions here, but none seem to work for me.
Using Chrome I get the message: CSRF token missing or incorrect
.
Using Internet Explorer I get the message: CSRF cookie not set
.
If I comment out 'django.middleware.csrf.CsrfViewMiddleware'
in settings.py, everything seems to work (although nothing gets mailed to the phony address of course.) I've tried putting a csrf_protect
decorator on my view, but it doesn't help. I've also tried commenting out the call to send_mail
, and I still get a CSRF failure, so apparently it's the ContactForm which is causing the problem.
(I'm using django 1.4.1.)
What do I need to do?
views.py
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from contact.forms import ContactForm
from django.template import RequestContext
from django.core.mail import send_mail
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('email', 'noreply@example.com'),
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
else:
form = ContactForm()
return render_to_response('contact_form.html', {'form': form}, context_instance=RequestContext(request))
def thanks(request):
return HttpResponse("Thanks for the feedback")
forms.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False)
message = forms.CharField()
contact_form.html
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
回答1:
If you want csrf protection, put the {% csrf_token %}
tag in your form.
If you don't want csrf protection, import and put the @csrf_exempt
decorator at the top of your view (see the docs).
来源:https://stackoverflow.com/questions/14074844/csrf-protection-in-django-1-4