Объект менеджера не имеет атрибута get_by_natural_key - PullRequest
0 голосов
/ 02 мая 2020

Я пытаюсь настроить пользовательскую модель пользователя в Django и считаю, что подавляющее большинство моих кодов верны, однако меня приветствует следующая ошибка:

'Менеджер 'У объекта нет атрибута' get_by_natural_key '

models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.core.validators import RegexValidator

USERNAME_REGEX = '^[a-zA-z0-9.+-]*$'

class MyAccountManager(BaseUserManager):
    def create_user(self, email, first_name, last_name, username, password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not first_name:
            raise ValueError("Users must have a first name")
        if not last_name:
            raise ValueError("Users must have a last name")
        if not username:
            raise ValueError("Users must hae an username")

        user = self.model(
                username=username,
                email=email,
                first_name=first_name, 
                last_name=last_name,
                )

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

    def create_superuser(self, email, username, password):
        user = self.create_user(
                username,
                email,
                first_name,
                last_name,
                password
                )
        user.is_admin = True
        user.is_Staff = False
        user.is_superuser = True
        user.save(using=self._db)
        return user

    def get_by_natural_key(self, email_):
        return self.get(code_number=email_)

    def __str__(self):
        return self.email

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

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app 'app_label'?"
        return True

class Account(AbstractBaseUser):
    objects = MyAccountManager()
    email = models.EmailField(
            verbose_name="email address", 
            max_length=60, 
            unique="True"
            )
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    username = models.CharField(
                max_length=300, 
                unique=True, 
                validators= [
                                RegexValidator(regex=USERNAME_REGEX,
                                          message='Username must be alphanumeric or contain numbers',
                                          code='invalid_username'
                          )],
                            )
    date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_headteacher = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)
    is_student = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    objects = MyAccountManager

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    def __str__(self):
        return self.email

    def get_short_name(self):
        return self.email

    def get_full_name(self):
        return self.email

    def has_perms(self,perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    def natural_key(self):
        return self.email

    def is_staff(self):
        self.is_admin

    @property
    def is_staff(self):
        self.is_admin


# Create your models here.

urls.py

from django.conf.urls import url
from django.contrib import admin

from Accounts.views import register, login_view, logout_view

urlpatterns =[
    ##url(r'^admin/', admin.site.urls),
    url(r'^register/$', register),
    url(r'^login/$', login_view),
    url(r'^logout/$', logout_view)
    ]

admin.py

from django.contrib import admin

# Register your models here.

from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .Forms import UserCreationForm from .models import Account, MyAccountManager

admin.site.unregister(Group)

class UserAdmin(BaseUserAdmin):
    add_form = UserCreationForm
    list_display = ('username', 'email', 'is_admin')
    list_filter = ('is_admin',)

    fieldsets = (
            (None, {'fields': ('username', 'email', 'password')}),
            ('Permissions', {'fields': ('is_admin',)})
        )
    search_fields = [('username'), ('email')]
    ordering = ('username', 'email')

    filter_horizontal = ()


admin.site.register(Account, UserAdmin)

**AUTH_USER_MODEL = 'Accounts.Account'**

Есть ли у кого-нибудь какие-либо предложения относительно того, как решить:

У объекта 'Manager' нет атрибута 'get_by_natural_key'

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...