禁止(403)CSRF验证失败。请求中止

时间:2021-01-12 19:16:31

I am making an app of login form but when I am running my app and click on login button the following error will occur

我正在制作登录表单的应用程序但是当我运行我的应用程序并单击登录按钮时,将发生以下错误

Forbidden (403) CSRF verification failed. Request aborted.

禁止(403)CSRF验证失败。请求中止。

the code of view.py is as:

view.py的代码如下:

from django.template import  loader
from django.shortcuts import render_to_response
from registration.models import Registration
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import redirect


def view_login(request,registration_id):
   t = loader.get_template('registration/login.html') 
   try:
         registration=Registration.objects.get(pk=registration_id)
   except Registration.DoesNotExist:
         return render_to_response("login.html",{"registration_id":registration_id})

def home(request,registration_id):
    if request.method == "POST":
      username = request.POST.get('user_name')
      password = request.POST.get('password')
      user = authenticate(username=username, password=password)
      if user is not None:
        if user.is_active:
          login(request, user)
        # success
          return render('registration/main_page.html',{'registration_id':registration_id},context_instance=RequestContext(user))
        else:
         #user was not active
           return redirect('q/',context_instance=RequestContext(user))
      else:
        # not a valid user
           return redirect('q/',context_instance=RequestContext(user))
    else:
       # URL was accessed directly
           return redirect('q/',context_instance=RequestContext(user))

4 个解决方案

#1


16  

You need to add {% csrf_token %} in your form

您需要在表单中添加{%csrf_token%}

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

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

like that :

像那样 :

<form>
    {% csrf_token %}
    <anything_else>
</form>

Also, you have to use RequestContext(request) everytime you use render_to_response :

此外,每次使用render_to_response时都必须使用RequestContext(request):

return render_to_response("login.html",
    {"registration_id":registration_id},
    context_instance=RequestContext(request))

And you have to import authenticate and login :

你必须导入身份验证和登录:

from django.contrib.auth import authenticate, login

#2


3  

Just comment 'django.middleware.csrf.CsrfViewMiddleware'

只需评论'django.middleware.csrf.CsrfViewMiddleware'

in your settings.py, which works for me:

在您的settings.py中,这对我有用:

//settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#3


2  

I encountered this problem while using the book "The Definitive Guide to Django" wherein version 1.1 is used. The book does not address the need for csrf_token verification that is mandated in later versions.

我在使用“Django权威指南”一书时遇到了这个问题,其中使用了1.1版本。本书未涉及在更高版本中强制要求的csrf_token验证。

To fix this issue, add:

要解决此问题,请添加:

from django.template import RequestContext

to the views.py file and this added argument for the render_to_response function:

到views.py文件和render_to_response函数的这个添加的参数:

context_instance = RequestContext(request)

Be sure to add {% csrf_token %} within the <form> tags in the template

请务必在模板中的

标记内添加{%csrf_token%}

#4


0  

When you have "Forbidden (403) CSRF verification failed. Request aborted" you can alternatively do:

如果您有“禁止(403)CSRF验证失败。请求已中止”您可以选择执行以下操作:

option (2) (not preferred)

选项(2)(不是首选)

import:

进口:

from django.template.context_processors import csrf

add to context:

添加到上下文:

context = {}
context.update(csrf(request))

return:

返回:

-Django > 1.9 has "context" instead of "context_instance"

-Django> 1.9有“context”而不是“context_instance”

return render_to_response("login.html",
    {"registration_id":registration_id},
    context=context)

option (3) (preferred)

选项(3)(首选)

import:

进口:

-instead of importing "render_to_response" import "render"

- 而不是导入“render_to_response”导入“渲染”

from django.shortcuts import render

return:

返回:

return render(request, "login.html", context)

Apparently option 3 is preferable, because "render" is shorter than "render_to_response", especially if you need to import and add stuff. I could imagine option 2 keeps a leaner context dict, but this seems trivial (?).

显然选项3是可取的,因为“render”比“render_to_response”短,特别是如果你需要导入和添加东西。我可以想象选项2保持更精简的上下文字典,但这似乎微不足道(?)。

For clarity:

为清楚起见:

Both solutions still need the {% csrf_token %} in your html form as mentioned above. And never turn off or comment the csrf middelware.

如上所述,这两种解决方案仍然需要html表单中的{%csrf_token%}。永远不要关闭或评论csrf middelware。

sources:

来源:

old Django 1.9 docs on RequestContext

RequestContext上的旧Django 1.9文档

Django 2 docs on the csrf processor

关于csrf处理器的Django 2文档

source explaining render is enough

源解释渲染就足够了

#1


16  

You need to add {% csrf_token %} in your form

您需要在表单中添加{%csrf_token%}

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

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

like that :

像那样 :

<form>
    {% csrf_token %}
    <anything_else>
</form>

Also, you have to use RequestContext(request) everytime you use render_to_response :

此外,每次使用render_to_response时都必须使用RequestContext(request):

return render_to_response("login.html",
    {"registration_id":registration_id},
    context_instance=RequestContext(request))

And you have to import authenticate and login :

你必须导入身份验证和登录:

from django.contrib.auth import authenticate, login

#2


3  

Just comment 'django.middleware.csrf.CsrfViewMiddleware'

只需评论'django.middleware.csrf.CsrfViewMiddleware'

in your settings.py, which works for me:

在您的settings.py中,这对我有用:

//settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#3


2  

I encountered this problem while using the book "The Definitive Guide to Django" wherein version 1.1 is used. The book does not address the need for csrf_token verification that is mandated in later versions.

我在使用“Django权威指南”一书时遇到了这个问题,其中使用了1.1版本。本书未涉及在更高版本中强制要求的csrf_token验证。

To fix this issue, add:

要解决此问题,请添加:

from django.template import RequestContext

to the views.py file and this added argument for the render_to_response function:

到views.py文件和render_to_response函数的这个添加的参数:

context_instance = RequestContext(request)

Be sure to add {% csrf_token %} within the <form> tags in the template

请务必在模板中的

标记内添加{%csrf_token%}

#4


0  

When you have "Forbidden (403) CSRF verification failed. Request aborted" you can alternatively do:

如果您有“禁止(403)CSRF验证失败。请求已中止”您可以选择执行以下操作:

option (2) (not preferred)

选项(2)(不是首选)

import:

进口:

from django.template.context_processors import csrf

add to context:

添加到上下文:

context = {}
context.update(csrf(request))

return:

返回:

-Django > 1.9 has "context" instead of "context_instance"

-Django> 1.9有“context”而不是“context_instance”

return render_to_response("login.html",
    {"registration_id":registration_id},
    context=context)

option (3) (preferred)

选项(3)(首选)

import:

进口:

-instead of importing "render_to_response" import "render"

- 而不是导入“render_to_response”导入“渲染”

from django.shortcuts import render

return:

返回:

return render(request, "login.html", context)

Apparently option 3 is preferable, because "render" is shorter than "render_to_response", especially if you need to import and add stuff. I could imagine option 2 keeps a leaner context dict, but this seems trivial (?).

显然选项3是可取的,因为“render”比“render_to_response”短,特别是如果你需要导入和添加东西。我可以想象选项2保持更精简的上下文字典,但这似乎微不足道(?)。

For clarity:

为清楚起见:

Both solutions still need the {% csrf_token %} in your html form as mentioned above. And never turn off or comment the csrf middelware.

如上所述,这两种解决方案仍然需要html表单中的{%csrf_token%}。永远不要关闭或评论csrf middelware。

sources:

来源:

old Django 1.9 docs on RequestContext

RequestContext上的旧Django 1.9文档

Django 2 docs on the csrf processor

关于csrf处理器的Django 2文档

source explaining render is enough

源解释渲染就足够了