我是 Django 的新手。我正在使用 django 创建一个网站。我已经为我的网站提供了注册和登录功能。
唯一的问题是登录成功后,每当我不小心重新加载浏览器时,它都会问我这个问题 about re-submitting details again
然后如果单击 continue ,它会向我显示此错误页面。 csrf token missing or incorrect
请告诉我应该怎么做才能避免这个错误?
答案 0 :(得分:0)
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`
答案 1 :(得分:0)
我给你举个例子,你可以这样尝试:
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})
试试这个方法。希望它对你有用。