首页 > 解决方案 > 登录 - 'AnonymousUser' 对象没有属性 '_meta'

问题描述

如果密码不正确,我会收到这种错误,我不知道为什么。我通常可以注册、登录、注销,但是当密码不正确时,就会发生错误。

我正在使用 AbstractBaseUser 注册表单。

我将不胜感激,并提前感谢您。

错误

Internal Server Error: /account/signin
Traceback (most recent call last):
  File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia\account\views.py", line 44, in sign_in
    login(request, user)
  File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\__init__.py", line 126, in login
    request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
  File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 241, in inner
    return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute '_meta'
[03/Jul/2021 04:21:48] "POST /account/signin HTTP/1.1" 500 78827
Not Found: /favicon.ico
[03/Jul/2021 04:21:48] "GET /favicon.ico HTTP/1.1" 404 2210

模型.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.contrib.auth import get_user_model  
from django.utils import timezone


class AccountManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, fname, lname, password, **extra_fields):

        email = self.normalize_email(email)
        user = self.model(
            email=email,
            fname=fname,
            lname=lname,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, fname, lname, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, fname, lname, password, **extra_fields)

    def create_superuser(self, email, fname, lname, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, fname, lname, password, **extra_fields)


class Account(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    fname = models.CharField(max_length=128)
    lname = models.CharField(max_length=128)
    phone = models.CharField(max_length=50, blank=True, null=True)
    bday = models.CharField(max_length=128, blank=True, null=True)
    country = models.CharField(max_length=128, blank=True, null=True)
    GENDER_CHOICES = (
        ("man", "Man"),
        ("female", "Female"),
        ("non_binary", "Non binary"),
        ("prefer_not_to_say", "Prefer not to say"),
    )

    gender = models.CharField(max_length=20,
                  choices=GENDER_CHOICES,
                  default="prefer_not_to_say")
    picture = models.ImageField(upload_to='images/%Y/%m/%d/', default="images/profile.png", blank=True, null=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    objects = AccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['fname', 'lname']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.fname.split()[0]

视图.py

from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from .forms import RegistrationForm, LoginForm, UserChangeForm, ChangePasswordForm
from .models import Account
from django.conf import settings

@csrf_exempt
def sign_in(request):
    form = LoginForm()
    context = {'form':form}
    if request.method == "POST":
        form = LoginForm(request.POST or None)
        Account.objects.get(email=request.POST.get('email'))
        if form.is_valid():
            data = form.cleaned_data
            user = authenticate(email=str(data['email']), password=str(data['password']))
            login(request, user)
            return redirect('/')

    return render(request, 'login.html', context)

表格.py

from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import Account

class RegistrationForm(forms.ModelForm):
    
    class Meta:
        model = Account
        fields = ('email', 'fname','lname')

    email = forms.CharField(widget=forms.EmailInput                (attrs={'class':'form-control',
                                                                           'placeholder':'Email'}))

    fname = forms.CharField(widget=forms.TextInput                 (attrs={'class':'form-control',
                                                                           'placeholder':'First Name'}))

    lname = forms.CharField(widget=forms.TextInput                 (attrs={'class':'form-control',
                                                                           'placeholder':'Last Name'}))

    password1 = forms.CharField(widget=forms.PasswordInput         (attrs={'class':'form-control',
                                                                           'placeholder':'Password'}))

    password2 = forms.CharField(widget=forms.PasswordInput         (attrs={'class':'form-control',
                                                                           'placeholder':'Confirmation Password'}))


    def clean_password2(self):
        # Check that the two password entries match         
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class LoginForm(forms.Form):
    email = forms.CharField(widget=forms.EmailInput(attrs={'class': "form-control",
                                                            'id': 'email',
                                                            "placeholder": "Email",
                                                            "type": "email",
                                                            "name": "email"}))

    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control",
                                                                'id': 'password',
                                                                "placeholder": "Password",
                                                                "type": "password",
                                                                "name": "password"}))


class ChangePasswordForm(forms.Form):
    current_password = forms.CharField(widget=forms.PasswordInput)
    new_password = forms.CharField(widget=forms.PasswordInput)
    repeat_password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = Account
        fields = ('current_password', 'new_password', 'repeat_password',)

标签: pythonpython-3.xdjangodjango-viewsdjango-login

解决方案


在我必须拥有的观点中,我找到了一个答案

if user is not None:
   login(request, user)

推荐阅读