微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CSRF 令牌丢失或不正确如何解决此错误?

如何解决CSRF 令牌丢失或不正确如何解决此错误?

我是 Django 的新手。我正在使用 django 创建一个网站。我已经为我的网站提供了注册登录功能

唯一的问题是登录成功后,每当我不小心重新加载浏览器时,它都会问我这个问题 about re-submitting details again

然后如果单击 continue ,它会向我显示错误页面csrf token missing or incorrect

请告诉我应该怎么做才能避免这个错误

解决方法

include {% csrf_token %} inside the form tag in the template and Just make sure,is there UserWarning in console like?: "A {% csrf_token %} was used in a template,but the context did not provide the value. This is usually caused by not using RequestContext."
if for any reason you are using render_to_response on Django 1.3 and above replace it with the render function. Replace this:

# Don't use this on Django 1.3 and above
return render_to_response('contact.html',{'form': form})
With this:

return render(request,'contact.html',{form: form})
The render function was introduced in Django version 1.3 - if you are using an ancient version like 1.2 or below you must use render_to_response with a a RequestContext:

# Deprecated since version 2.0
return render_to_response('contact.html',{'form': form},context_instance=RequestContext(request))`enter code here`
,

我给你举个例子,你可以这样尝试:

from django.shortcuts import render,get_object_or_404,redirect

def login_view(request):
    form = UserLoginForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            user_obj = form.cleaned_data.get('user_obj')
            login(request,user_obj)
            return redirect('home') # if you want to redirect same page then,return redirect('this function name in urls.py')

    return render(request,'registration/login.html',{'form': form})

试试这个方法。希望它对你有用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。