这是一个被广泛提问的问题,但大多数都有不同的情况,我也相信我的。
以下是我的项目详情
apps.ulrs.py:
urlpatterns = [
url(r'^index/$', views.IndexView, name='index'),
url(r'^signup/$', views.signupview, name='sign_up'),
]
models.py:
from django.db import models
from django.core.urlresolvers import reverse
#from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Registration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.CharField(max_length = 250)
password = models.CharField(max_length = 250)
email = models.CharField(max_length = 250)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Registration.objects.create(user=instance)
instance.registration.save()
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from .forms import SignUpForm
#from django.corecontext_processors import csrf
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.views import generic
class IndexView(generic.View):
templet_name = 'user_info/index.html'
def signupview(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('registration_form.html')
else:
form = SignUpForm()
#return render(request,'user_info/registration_form.html', {'form': form})
return render_to_response('user_info/registration_form.html', {'form': form, }, context_instance = RequestContext(request))
我做了一些研究,我发现我们需要在views.py中导入“csrf”,所以我尝试了下面的内容:
#from django.corecontext_processors import csrf
但根据我的理解,它自django 1.8以来已被弃用。如果我错了,请纠正我。我使用的是python 3.6和django 1.11。那么,我应该为'csrf'导入的库是什么?
我的html文件里面有{%csrf_token%}标签:
{% block title %}register{% endblock %}
{% block body %}
{% block content %}
<h2>Sign up</h2>
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
{% endblock %}
{% endblock %}
我得到的确切错误是:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
答案 0 :(得分:1)
不要使用render_to_response
,它已经过时了。取消注释使用render
的行并改为使用该行。
return render(request,'user_info/registration_form.html', {'form': form})
使用render
时,无需在视图中使用RequestContext
或csrf上下文处理器。