首页 > 解决方案 > 验证没有值

问题描述

在表单中我尝试登录用户,但我有如下消息

“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)

标签: djangouser-interfaceauthenticationview

解决方案


推荐阅读