如何通过编写新的admin.ModelAdmin在Wagtail 1.8中创建自定义用户模型?

时间:2019-01-29 08:52:22

标签: python wagtail django-users

在Wagtail 1.8项目中,我试图创建一个自定义用户模型,该模型不使用用户名,仅使用电子邮件。我希望能够定义诸如is_training之类的额外变量,并将其显示在admin/users/edit下管理区域的编辑表单中。

现在我已经有EmailUser(CustomUser),但是我无法将boolean或Checkbox添加到Admin-Edit Panel。

class AbstractEmailUser(AbstractBaseUser, PermissionsMixin):
    """Abstract User with the same behaviour as Django's default User.
    AbstractEmailUser does not have username field. Uses email as the
    USERNAME_FIELD for authentication.
    Inherits from both the AbstractBaseUser and PermissionMixin.
    The following attributes are inherited from the superclasses:
        * password
        * last_login
        * is_superuser
    """

    email = models.EmailField(
        verbose_name=_('email address'),
        max_length=255,
        unique=True,
        db_index=True,
        error_messages={
            'unique': _("A user with that e-mail already exists."),
        }
    )
    email_new = models.EmailField(
        verbose_name=_('new email address'),
        max_length=255,
        unique=True,
        error_messages={
            'unique': _("A user with that e-mail already exists."),
        },
        null=True, blank=True
    )
    first_name = models.CharField(
        max_length=150,
        verbose_name=_('first name'),
        blank=True,
    )
    last_name = models.CharField(
        max_length=150,
        verbose_name=_('last name'),
        blank=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(
        verbose_name=_('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    is_training = models.BooleanField(
        verbose_name=_('training'),
        default=False,
        help_text=_(
            'Designates whether this user participates in training and therefore has special access to the'
            'training site. '
        ),
    )
    date_joined = models.DateTimeField(
        verbose_name=_('date joined'),
        default=timezone.now
    )
    last_downloads_check = models.DateTimeField(
        verbose_name=_('Last downloads check'),
        help_text=_('The last time the user checked the latest downloads.'),
        default=timezone.now
    )
    last_news_check = models.DateTimeField(
        verbose_name=_('Last news check'),
        help_text=_('The last time the user checked the latest news in the consultants only area.'),
        default=timezone.now
    )

    objects = EmailUserManager()

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

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        abstract = True

    def get_full_name(self):
        """Return first_name plus last_name, with a space in between."""
        return "{} {}".format(self.first_name, self.last_name).strip()

    def get_short_name(self):
        """Returns the short name for the user."""
        return self.first_name

    def get_identifier(self):
        if self.first_name and self.last_name:
            return self.get_full_name()
        else:
            return self.email

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this User."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

    def __unicode__(self):
        return 'email="{}" firstName="{}" lastName="{}" admin={}'.format(
            self.email, self.first_name, self.last_name, self.is_staff, self.is_training
        )

据我了解,我需要编写一个新的ModelAdmin,因为我的EmailUser没有用户名:

from __future__ import unicode_literals

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from .models import EmailUser


class EmailUserAdmin(admin.ModelAdmin):
    list_display = ('email', 'first_name', 'last_name', 'is_training')
    list_filter = ('is_staff', 'is_superuser')


admin.site.register(User, EmailUserAdmin)

通过编写ModelAdmin,我陷入了困境。我不知道如何使用w管理表单来使其与我的模型兼容。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您还需要向Wagtail的ModelAdmin注册,通常是在wagtail_hooks.py文件中完成。以下是您可能需要调整的其他几个示例:

from wagtail.contrib.modeladmin.options import (
    ModelAdmin, modeladmin_register
)

from .models import EmailUser


class UserAdmin(ModelAdmin):
    model = EmailUser
    menu_label = 'Users'
    menu_icon = 'fa-folder-open'
    add_to_settings_menu = True
    list_display = ('email', 'first_name', 'last_name', 'is_training')
    list_filter = ('is_staff', 'is_superuser')
    ordering = ('email',)


modeladmin_register(UserAdmin)

在此处查看文档:{​​{3}}

祝你好运!