Django创建CustomUser模型

时间:2017-10-22 17:38:52

标签: python django

民间,

我试图通过扩展Django提供的AbstractBaseUser模型来创建自己的User模型。

但是,迁移时我一直收到以下错误: open override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground(notification:)), name: .UIApplicationWillEnterForeground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground(notification:)), name: .UIApplicationDidEnterBackground, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func applicationWillEnterForeground(notification: NSNotification) { print("will enter foreground") } @objc private func applicationDidEnterBackground(notification: NSNotification) { print("did enter background") }

到目前为止,我所做的工作如下:

ValueError: The field admin.LogEntry.user was declared with a lazy reference to '<app_name>.user', but app '<app_name>' doesn't provide model 'user'. 中将CustomUser类与CustomUserManager一起添加了相关字段和所有字段。

app/models.py我添加了这个:

app/admin.py

除此之外,还有from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from <app_name>.models import CustomUser class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('email',) class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email',) def clean_username(self): username = self.cleaned_data["username"] try: get_user_model().objects.get(username=username) except get_user_model().DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreationForm fieldsets = ( (None, {'fields': [('username', 'password'),]}), (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (('Important dates'), {'fields': ('last_login', 'date_joined')}), ) admin.site.register(CustomUser, CustomUserAdmin)

seetings.py

到目前为止我发现的所有内容都表明上面给出的代码应该能够实现这一点,但它并没有。我已经花了4-5个小时,我仍然无法理解它。有人请帮忙

1 个答案:

答案 0 :(得分:1)

像这样创建用户模型:

st:envFactorEMF a st:studyVariable ; # << this isn't recognized
  st:subject tax:1758 ;
  st:signal -.00043 .

不要忘记添加自定义字段!

使用自定义管理员:

from django.core import validators
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import UserManager

class User(AbstractBaseUser, PermissionsMixin):

    username = models.CharField(_('username'), max_length=75, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, numbers and '
                    'underscores characters'),
        validators=[
            validators.RegexValidator(re.compile('^[\w]+$'), 
            _('Enter a valid username.'), 'invalid')
        ])
    first_name = models.CharField(_('first name'), max_length=254, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), max_length = 254, unique = True, null = True)
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['first_name']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.username

然后最后将其添加到您的设置中:

@admin.register(models.User)
class CustomUserAdmin(UserAdmin):
    list_display = ('name', 'username', 'is_staff', )
    list_filter = ('is_staff', )
    search_fields = ('first_name', 'last_name', 'username', )
    readonly_fields = ('date_joined', 'last_login', )
    fieldsets = (
        (None, {
            'fields': ('username', 'password')
        }),
        ("Personal Information", {
            'fields': ('first_name', 'last_name', 'email')
        }),
        ("Permissions", {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
        }),
        ("Important Dates", {
            'fields': ('last_login', 'date_joined')
        }),
    )

我的GitHub repository可以找到工作演示。