我有以下文件:
#views.py
from django.views.generic.edit import FormView
from django.views.generic.base import TemplateView
from braces.views import AnonymousRequiredMixin, CsrfExemptMixin
#exempting from Csfr as the worst it can do is making lots of new users
class LogonView(CsrfExemptMixin, AnonymousRequiredMixin, FormView):
"the page to create a new user"
from .forms import LogonForm as form_class
template_name = "registration/logon.html"
from django.urls import reverse_lazy
authenticated_redirect_url = reverse_lazy("success")
success_url = authenticated_redirect_url
def form_valid(self, form):
u = form.save(commit=False)
u.set_password(form.cleaned_data["password"])
u.save()
from django.contrib.auth import login
login(self.request, u)
return super().form_valid(form)
class SuccessView(TemplateView):
template_name = "registration/success.html"
#forms.py
from django import forms as f
class LogonForm(f.ModelForm):
"The form to create a new user"
# repeat the password form
password2 = f.CharField(
label="Please repeat your password",
widget=f.PasswordInput,
)
class Meta:
from django.contrib.auth.models import User as model
fields = ("username", "email", "first_name", "last_name", "password")
widgets = {"password": f.PasswordInput, }
def clean(self):
c = super().clean()
pwd = c.get("password")
if pwd and pwd == c.get("password2"):
return c
raise f.ValidationError(
"You need to repeat the passwords identically")
#urls.py
from django.urls import path, include
from .views import *
urlpatterns = [
path('', include('django.contrib.auth.urls')),
path("logon/", LogonView.as_view(), name="logon"),
path("success/",SuccessView.as_view(),name="success")
]
当我尝试访问/ login并填写生成的表单时,它给了我403 CSFR错误。
奇怪的是,用户仍然创建并且登录仍然成功, 因此,如果我尝试重新加载错误页面,它会将我重定向到/ success页面