CSRF Protection in Django 1.4

寵の児 提交于 2019-11-28 05:25:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!