Django中的csrf错误

发布于 2024-09-08 16:42:28 字数 1109 浏览 14 评论 0原文

我想实现我的网站的登录。我基本上将 Django 书中的以下内容复制并粘贴在一起。但是,在提交注册表单时,我仍然收到错误(CSRF 验证失败。请求中止。)。有人可以告诉我是什么引发了这个错误以及如何修复它吗?

这是我的代码:

views.py:

# Create your views here.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    return render_to_response("registration/register.html", {
        'form': form,
    })

register.html:

<html>
<body>

{% block title %}Create an account{% endblock %}

{% block content %}
  <h1>Create an account</h1>

  <form action="" method="post">{% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="Create the account">
  </form>
{% endblock %}
</body>
</html>

I want to realize a login for my site. I basically copied and pasted the following bits from the Django Book together. However I still get an error (CSRF verification failed. Request aborted.), when submitting my registration form. Can somebody tell my what raised this error and how to fix it?

Here is my code:

views.py:

# Create your views here.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    return render_to_response("registration/register.html", {
        'form': form,
    })

register.html:

<html>
<body>

{% block title %}Create an account{% endblock %}

{% block content %}
  <h1>Create an account</h1>

  <form action="" method="post">{% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="Create the account">
  </form>
{% endblock %}
</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

離人涙 2024-09-15 16:42:28

我遇到了完全相同的问题 - 蓝辣椒的回答让我走上了正轨。将 RequestContext 添加到表单视图可以解决该问题。

from django.template import RequestContext

并且:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
           new_user = form.save()
           return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    c = {'form': form}
    return render_to_response("registration/register.html", c, context_instance=RequestContext(request))

这为我解决了这个问题。

I was having the exact same issue - and Blue Peppers' answer got me on the right track. Adding a RequestContext to your form view fixes the problem.

from django.template import RequestContext

and:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
           new_user = form.save()
           return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    c = {'form': form}
    return render_to_response("registration/register.html", c, context_instance=RequestContext(request))

This fixed it for me.

彩扇题诗 2024-09-15 16:42:28

我正在使用 Django 1.2.3,我遇到了一些间歇性问题:

要做的事情:

确保模板中存在 csrf 令牌

<form action="" method="post">{% csrf_token %}

使用 RequestContext

return render_to_response('search-results.html', {'results' : results}, context_instance=RequestContext(request) )

如果 GET 由相同的视图函数处理,请确保也使用 RequestContext 并呈现相同的模板。

即:

if request.method == 'GET':
    ...
    return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request) )
elif request.method == 'POST':
    ...
    return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request))

不是:

if request.method == 'GET':
    ...
    return render_to_response('search-results.html', {'results':results})
elif request.method == 'POST':
    ...
    return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request))

确保“django.middleware.csrf.CsrfViewMiddleware”在您的settings.py中列出

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

I'm using Django 1.2.3, I had a few intermittent problems:

Things to do:

Ensure the csrf token is present in your template:

<form action="" method="post">{% csrf_token %}

Use a RequestContext:

return render_to_response('search-results.html', {'results' : results}, context_instance=RequestContext(request) )

Make sure you use a RequestContext for GETs as well, if they are handled by the same view function, and render the same template.

i.e:

if request.method == 'GET':
    ...
    return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request) )
elif request.method == 'POST':
    ...
    return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request))

not:

if request.method == 'GET':
    ...
    return render_to_response('search-results.html', {'results':results})
elif request.method == 'POST':
    ...
    return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request))

Ensure 'django.middleware.csrf.CsrfViewMiddleware' is listed in your settings.py

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)
枕花眠 2024-09-15 16:42:28

假设您使用的是 Django 1.2.x,只需在 {{form.as_p}} 之前添加以下内容:

{% csrf_token %}

要了解原因,请查看 < a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/" rel="noreferrer">CSRF 文档

Assuming you're on Django 1.2.x, just add this before {{form.as_p}}:

{% csrf_token %}

And to understand WHY, check out the CSRF docs

晨曦÷微暖 2024-09-15 16:42:28

您需要将 csrf(request) 添加到您的上下文中。

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    con = {'form': form}
    con.update(csrf(request))
    return render_to_response("registration/register.html", con)

为此,您可能需要将上下文转换为 Context 对象,而不是 dict,但原理是合理的。

You need to add csrf(request) to your context.

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.context_processors import csrf

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/books/")
    else:
        form = UserCreationForm()
    con = {'form': form}
    con.update(csrf(request))
    return render_to_response("registration/register.html", con)

You might need to turn your context into a Context object for this, not a dict, but the principle is sound.

ヅ她的身影、若隐若现 2024-09-15 16:42:28

如果您不想将 {% csrf_token %} 添加到每个表单,请将这 2 个中间件添加到设置文件中。

MIDDLEWARE_CLASSES = (
    #...
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.csrf.CsrfResponseMiddleware',
)

Add these 2 middlewares to the settings file if you don't want to add {% csrf_token %} to each form.

MIDDLEWARE_CLASSES = (
    #...
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.csrf.CsrfResponseMiddleware',
)
奢华的一滴泪 2024-09-15 16:42:28

稍后回答。

现在可以使用 render 代替 context_instance=RequestContext(request)

from django.shortcuts import render
return render(request, "registration/register.html", {
        'form': form,
    })

Later answer.

Now render can use instead of context_instance=RequestContext(request)

from django.shortcuts import render
return render(request, "registration/register.html", {
        'form': form,
    })
审判长 2024-09-15 16:42:28

如果您打算使用 {% csrf_token %},请尝试从 settings.py 的中间件列表中删除以下行:

'django.middleware.csrf.CsrfViewMiddleware',

为我工作......

Try removing the following line from your settings.py's MIDDLEWARE list if you intend to use the {% csrf_token %}:

'django.middleware.csrf.CsrfViewMiddleware',

Worked for me......

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文