Forbidden (403) CSRF 验证失败.请求中止 [英] Forbidden (403) CSRF verification failed. Request aborted
本文介绍了Forbidden (403) CSRF 验证失败.请求中止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个登录表单的应用程序,但是当我运行我的应用程序并单击登录按钮时,会发生以下错误
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
禁止 (403)CSRF 验证失败.请求已中止.
view.py 的代码如下:
the code of view.py is as:
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))
推荐答案
您需要在表单中添加{% csrf_token %}
https://docs.djangoproject.com/en/2.2/ref/csrf/
像这样:
<form>
{% csrf_token %}
<anything_else>
</form>
此外,每次使用 render_to_response
时都必须使用 RequestContext(request) :
Also, you have to use RequestContext(request) everytime you use render_to_response
:
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
这篇关于Forbidden (403) CSRF 验证失败.请求中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文