Django:没有属性 'get_by_natural_key'

Django: no attribute 'get_by_natural_key'

我目前正在尝试实施我自己的用户模型。为此,我创建了一个新应用 "accounts"。但是每次我尝试创建新用户时,我都会收到以下错误:

AttributeError: 'AnonymousUser' object has no attribute '_meta'

帐户 - models.py:

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)



#User Model Manager
class UserManager(BaseUserManager):
    def create_user(self, username, password=None):
        """
        Creates and saves a User with the given username and password.
        """
        if not username:
            raise ValueError('Error: The User you want to create must have an username, try again')

        user = self.model(
            user=self.normalize_username(username),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_staffuser(self, username, password):
        """
        Creates and saves a staff user with the given username and password.
        """
        user = self.create_user(
            username,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password):
        """
        Creates and saves a superuser with the given username and password.
        """
        user = self.create_user(
            username,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser):

    #User fields
    user = models.CharField(verbose_name='username',max_length=30,unique=True)
    bio = models.TextField(max_length=5000, blank=True, null=True)
    pubpgp = models.TextField(blank=True, null=True)

    #Account typs
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) # a admin user; non super-user
    admin = models.BooleanField(default=False) # a superuser
    # notice the absence of a "Password field", that's built in.

    USERNAME_FIELD = 'user'
    REQUIRED_FIELDS = [] # Username & Password are required by default.

    def get_full_name(self):
        # The user is identified by their Username ;)
        return self.user

    def get_short_name(self):
        # The user is identified by their Username address
        return self.user
    def __str__(self):
        return self.user

    def has_perm(self, perm, obj=None):
        """Does the user have a specific permission?"""
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        """Does the user have permissions to view the app `app_label`?"""
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        """Is the user a member of staff?"""
        return self.staff

    @property
    def is_admin(self):
        """Is the user a admin member?"""
        return self.admin

    @property
    def is_active(self):
        """Is the user active?"""
        return self.active

    objects = UserManager()

之后我跳回 settings.py 并将自定义用户模型添加到我的实际博客应用程序中:

AUTH_USER_MODEL = 'accounts.User'

而且我还添加了

INSTALLED_APPS = [
...
    'accounts',
...   
]

所有这些用户 model/django 的东西对我来说有点新,我不知道错误 "AttributeError: 'Manager' object has no attribute 'get_by_natural_key'" 是什么意思。

谢谢 :D

编辑:AttributeError:'UserManager' 对象没有属性 'normalize_username'

normalize_username属于AbstractBaseUser,您可以试试下面的代码。

signup 视图中,当您保存表单时,您已经获得了用户 (form.save())。因为身份验证的原因是验证一组凭据并获取用户(但我们已经有用户)

在这一行:user = authenticate(username=username, password=raw_password)authenticate 方法将 request 作为第一个参数,所以它应该是:user = authenticate(request, username=username, password=raw_password),因此你得到了错误 'AnonymousUser' 对象没有属性 '_meta'.

尝试:

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('post_list')

编辑用户管理器:

将所有创建的用户重新命名为其他名称(例如 my_user),因为您有两个同名的变量(USERNAME_FIELD 和创建的用户)

这里是create_usercreate_superuser

的签名

create_user(*username_field*, password=None, **other_fields) create_superuser(*username_field*, password, **other_fields)

他们把USERNAME_FIELD作为第一个参数,而你的是user

class UserManager(BaseUserManager):
    def create_user(self, user, password=None):
        """
        Creates and saves a User with the given username and password.
        """
        if not user:
            raise ValueError('Error: The User you want to create must have an username, try again')

        my_user = self.model(
            user=self.model.normalize_username(user),
        )

        my_user.set_password(password)
        my_user.save(using=self._db)
        return my_user

    def create_staffuser(self, user, password):
        """
        Creates and saves a staff user with the given username and password.
        """
        my_user = self.create_user(
            user,
            password=password,
        )
        my_user.staff = True
        my_user.save(using=self._db)
        return my_user

    def create_superuser(self, user, password):
        """
        Creates and saves a superuser with the given username and password.
        """
        my_user = self.create_user(
            user,
            password=password,
        )
        my_user.staff = True
        my_user.admin = True
        my_user.save(using=self._db)
        return my_user

希望对您有所帮助。