django管理站点更改表单字段

时间:2018-07-16 06:08:19

标签: python django django-admin

我是django的新手。我将在管理站点中为用户创建一个更改表单。

MyUser:

class MyUser(AbstractUser):
    """
    The customized user model for the project
    It has one-to-one relations to Profile.
    """

    profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT)

个人资料:

class Profile(models.Model):
    """User profile model, specifying the user's general preferences and language"""
    GENDERS = (
        ('male', _('Male')),
        ('female', _('Female')),
    )

    TYPICAL_USAGES = (
        ('personal', _('Personal')),
        ('academic', _('Academic')),
        ('business', _('Business')),
    )


    gender = models.CharField(_("gender"), max_length=10, choices=GENDERS)
    # We use full_name instead of the default 'first_name' and 'last_name', to enable non-personal users
    full_name = models.CharField(_("full name"), max_length=60)
    # A valid two-letter language code which is used when the user is logged in
    language = models.CharField(_("language"), max_length=2, choices=settings.LANGUAGES, blank=True)
    typical_usage = models.CharField(_("typical usage"), max_length=10, choices=TYPICAL_USAGES)

    country = models.ForeignKey(Country, on_delete=models.PROTECT, verbose_name=_("country"), blank=True, null=True)
    province = models.ForeignKey(Province, on_delete=models.PROTECT, verbose_name=_("province"), blank=True, null=True)
    city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name=_("city"), blank=True, null=True)
    is_subscribed = models.BooleanField(_("newsletter subscription"), default=True)

我当前的admin.py:

class MyUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = MyUser


class MyUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = MyUser


class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm

    def has_add_permission(self, request):
        return False


admin.site.register(MyUser, MyUserAdmin)

现在,我希望change_form包含profile的所有字段和MyUser的某些字段(不包括firstnamelastnameusername),我想要用户名是用户的电子邮件。当我搜索时,我的第二个要求可以通过这种方式完成:

class MyUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = MyUser

    def save(self, commit=True):
        user = super(MyUserChangeForm, self).save(commit=False)
        user.username = self.cleaned_data['email']
        if commit:
            user.save()
        return user

我不确定这是否是最好的方法。如果有人可以提供指导,我将很感激。

0 个答案:

没有答案