django - 验证没有值
问题描述
在表单中我尝试登录用户,但我有如下消息
“AnonymousUser”对象没有属性“_meta”
在视图 sign_in 我的用户也有 None 值,我的用户名和密码是正确的,我确定。哪里有问题?在视图 sign_in 我的用户也有 None 值,我的用户名和密码是正确的,我确定。哪里有问题?
from django import forms
from django.contrib.auth.models import User
from django.core.validators import MinLengthValidator
from django.utils.translation import gettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field, Column
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
class UserSignUpForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserSignUpForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['last_name'].required = True
who = forms.ChoiceField(
choices=[('student', 'Student'), ('teacher', 'Teacher')],
label="",
required=True,
widget=forms.RadioSelect(
attrs={'style':'max-width: 20em; ', 'autocomplete':'off', })
)
password = forms.CharField(
label="Password",
validators=[MinLengthValidator(8, message="Minimum 8 characters")],
widget=forms.PasswordInput(attrs={'autocomplete':'off'}))
confirm_password = forms.CharField(
label="Confirm password",
validators=[MinLengthValidator(8, message="Minimum 8 characters"), ],
widget=forms.PasswordInput(attrs={'autocomplete':'off'}))
class Meta:
model = User
fields = ('who', "username", 'first_name', 'last_name', "password", )
help_texts = {"username": None}
widgets = {
'username': forms.TextInput(attrs={}),
'first_name': forms.TextInput(attrs={}),
'last_name': forms.TextInput(attrs={}),
}
def clean(self):
cleaned_data = super(UserSignUpForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
msg = _(f'Password and confirm password does not match')
self.add_error('password', msg)
self.add_error('confirm_password', msg)
helper = FormHelper()
helper.form_tag = 'false'
helper.attrs = {"novalidate": True, 'autocomplete':'off'}
helper.form_class = 'form-horizontal'
helper.field_class = 'col-md-8 '
helper.label_class = 'col-md-4'
helper.layout = Layout(
Row(
Column(
Field('who', css_class='form-group', style='margin-left:200px'),
Field('username', css_class='form-group ', style=''),
Field('first_name', css_class='form-group'),
Field('last_name', css_class='form-group'),
Field('password', css_class='form-group'),
Field('confirm_password', css_class='form-group'),
FormActions(
Submit('save', 'Sign up', css_class="btn-primary"),
Submit('cancel', 'Cancel'),
),
)
)
)
class UserLoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(
attrs={
"class": "form-control"
}))
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"class": "form-control",
"id": "user-password"
}
)
)
def clean_username(self):
username = self.cleaned_data.get("username")
qs = User.objects.filter(username__iexact=username) # thisIsMyUsername ==
thisismyusername
if not qs.exists():
raise forms.ValidationError("This is an invalid user.")
if qs.count() != 1:
raise forms.ValidationError("This is an invalid user.")
return username
helper = FormHelper()
helper.form_tag = 'false'
helper.attrs = {'autocomplete':'off'}
helper.form_class = 'form-horizontal'
helper.field_class = 'col-md-8 '
helper.label_class = 'col-md-4'
helper.layout = Layout(
Row(
Column(
Field('username', css_class='form-group ', style=''),
Field('password', css_class='form-group'),
FormActions(
Submit('submit', 'Sign in', css_class="btn-primary"),
Submit('cancel', 'Cancel'),
),
)
)
)
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from .forms import UserSignUpForm, UserLoginForm
from .models import Teacher, Student
def index(request):
return render(request, 'school/index.html')
def sign_up(request):
context ={}
who ={"teacher": Teacher, "student": Student}
form = UserSignUpForm(request.POST or None)
if request.method == "POST":
if form.is_valid() and request.POST.get("who"):
user = form.save()
person = who[request.POST.get("who")]
person(user=user).save()
return render(request, 'school/index.html')
context['form'] = form
return render(request, 'registration/sign_up.html', context)
def sign_in(request):
context = {}
form = UserLoginForm(request.POST or None)
context['form'] = form
if form.is_valid():
print('test1')
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
print('test3')
attempt = request.session.get('attempt') or 0
request.session['attempt'] = attempt + 1
return render(request, 'registration/sign_in.html', context)
return render(request, 'registration/sign_in.html', context)
解决方案
推荐阅读
- python-3.x - 如何访问 GStreamer webrtcbin 中作为 gobject.GParamSpec 提供的值?
- python - 无法在 Tkinter 中使用两个不同的按钮在我从 Python 中的 Selenium 打开的同一个 chrome 窗口上执行任务
- google-bigquery - 如何从谷歌 bigquery 中的地理点创建多边形
- laravel - 尝试使用 axios 补丁方法更新购物车项目数量:错误:请求失败,状态码 405
- android - Moshi 转换器阵列
- dc.js - 为每个类别创建直方图
- windows - 如何使用 curl 检查站点是否存在并在 Windows 中不存在时运行脚本
- c# - 通过脚本传递变量的问题
- microsoft-graph-api - 您无权访问 Teams 中的默认目录组织。选择其他组织,或联系您的管理员了解更多详细信息。(Microsoft Teams)
- android - 错误:覆盖 AOSP 10 中 base_rules.mk 的命令