Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - CSRF Token missing or incorrect

Beginner at Django here, I've been trying to fix this for a long time now. I do have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware classes and I do have the token in my post form.

Heres my code, what am I doing wrong?

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from chartsey.authentication.forms import RegistrationForm
from django.template import RequestContext
from django.core.context_processors import csrf

def register(request):

    if request.method == 'POST':
        c = RequestContext(request.POST, {})
        form = RegistrationForm(c)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/")
    else:
        form = RegistrationForm()

    return render_to_response("register.html",  {'form': form,  }, )

Here's my Template:

{% block content %}

    <h1>Register</h1>
    <form action="" method="POST"> {% csrf_token %}
        {{ form.as_p }}
    <input type="submit" value="Submit">
    </form>

{% endblock %}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: This answer is from 2011. CSRF is easy today.

These days you should be using the render shortcut function return render(request, 'template.html') which uses RequestContext automatically so the advice below is outdated by 8 years.

  1. Use render https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/
  2. Add CSRF middleware https://docs.djangoproject.com/en/2.2/ref/csrf/
  3. Use the {% csrf_token %} template tag
  4. Confirm you see the CSRF token value being generated, AND submitted in your form request

Original Response

My guess is that you have the tag in the template but it's not rendering anything (or did you mean you confirmed in the actual HTML that a CSRF token is being generated?)

Either use RequestContext instead of a dictionary

render_to_response("foo.html", RequestContext(request, {}))

Or make sure you have django.core.context_processors.csrf in your CONTEXT_PROCESSORS setting.

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

Or add the token to your context manually


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...