用于创建AbstractUser扩展模型的Django管理表单 [英] Django admin form for creating AbstractUser extended model

查看:99
本文介绍了用于创建AbstractUser扩展模型的Django管理表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展/继承AbstractUser的自定义用户模型。我还希望管理员中的用户创建表单匹配,但是由于某种原因,我只能让它显示用户名和密码字段。没有其他的。



我发现特别有趣的是,我对admin.py中的这3个字段所做的更改反映在创建表单中,但是其他字段从未显示。因此,例如,我可以更改password1的帮助文本或标签,并将其呈现为表单,而其他字段则不显示。



此外,如果我设置了extend UserAdmin并进行注册(如下代码所示),我得到了普通用户的3字段创建视图,但是如果我扩展ModelAdmin,我将获得所有字段,但是不能使用密码更新表单。它是404s。



值得注意的是,对象列表中的链接是用户,而不是模型调用时的 CommonUser,但这可能是某个地方的类元。






admin.py



<$从django.contrib导入p $ p> 从django.contrib.auth.admin导入admin
从django.contrib.auth.forms导入UserAdmin
导入UserChangeForm,UserCreationForm
从模型导入CommonUser,帐户,注册表
从Django导入表单


类MyUserChangeForm(UserChangeForm):
类Meta(UserChangeForm.Meta):
模型= CommonUser


class MyUserCreationForm(UserCreationForm):

密码= form.CharField(
label ='Password',
max_length = 32,需要
=正确,
widget = forms.PasswordInput,


password2 = forms.CharField(
label ='Confirm',
max_length = 32,需要
=正确,
widget = forms.Passwo rdInput,
help_text =确保它们匹配!,



类Meta(UserCreationForm.Meta):
模型= CommonUser
个字段= ['用户名','密码','密码2','电子邮件',
'first_name','last_name','address','city','state','zipcode',
'phone1','phone2',]
help_texts = {
'password':'必须至少包含8个字符。',
}


def clean_username(self):
用户名= self.cleaned_data ['username']
尝试:
CommonUser.objects.get(username = username)
除了CommonUser .DoesNotExist:
返回用户名
加薪表单。ValidationError(self.error_messages ['duplicate_username'])


class MyUserAdmin(UserAdmin):
形式= MyUserChangeForm
add_form = MyUserCreationForm
字段集= UserAdmin.fieldsets +(
('Personal info',{'fields':('address','phone1',)}),


admin.site.register(Comm onUser,MyUserAdmin)

(。段)model.py

 从django.contrib.auth.models import AbstractUser 

class CommonUser(AbstractUser):
带有一般信息的用户抽象。

WORK_STATES =(
('FL','FL'),


地址= models.CharField(max_length = 50)
city = models.CharField(max_length = 30)
state = models.CharField(max_length = 2,default ='FL',choices = WORK_STATES)
邮政编码= models.CharField(max_length = 10)
phone1 = models.CharField(max_length = 15)
phone2 = models.CharField(max_length = 15,null = True)
gets_email_updates = models.BooleanField(default = False)






来源



在管理员Django
使用Django auth UserAdmin对于自定义用户模型
https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#a-完整示例

解决django.contrib.auth.admin中的方案

UserAdmin还将设置 add_fieldsets属性,该属性设置要在添加用户视图上显示的字段。由于UserAdmin设置了该字段,因此您需要覆盖它以设置自己的字段。



这里是一个示例:

  class CustomUserAdmin(UserAdmin):
#...在这里编码...

字段集=(
(无,{'fields ':('email',)}),
(_('Personal info'),{'fields':('first_name','last_name')}),
(_('Permissions '),{'fields':('is_active','is_staff','is_superuser',
'groups','user_permissions')}),
(_('重要日期'),{ 'fields':('last_login','date_joined')}),

add_fieldsets =(
(None,{
'classes':('wide',,) ,
'fields':('email','first_name','last_name','password1',
'password2')}
),

希望这会有所帮助!


I've got a custome user model that extends/inherits AbstractUser. I also want the user creation form in admin to match, but for some reason I can only get it to show Username and Password fields. Nothing else.

What I find particularly interesting is that the changes I makes to those 3 fields in my admin.py reflect in the creation form, but the additional fields never show up. So for example I can change the helptext or label of a password1 and is renders that in the form, but the other fields don't.

Also, if I set extend UserAdmin and register that (as is shown in the code below) I get the 3 field creation view of a generic user, but if I extend ModelAdmin I get ALL my fields, but can't use the password update form. It 404s.

Of note also is that the link into the object list is 'User', not 'CommonUser' as my model is called, but that is probably a class meta somewhere.


admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from models import CommonUser, Account, Registry
from django import forms


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


class MyUserCreationForm(UserCreationForm):

 password = forms.CharField(
    label='Password',
    max_length = 32,
    required=True,
    widget=forms.PasswordInput,
    )

password2 = forms.CharField(
    label='Confirm',
    max_length = 32,
    required=True,
    widget=forms.PasswordInput,
    help_text="Make sure they match!",
    )


class Meta(UserCreationForm.Meta):
    model = CommonUser
    fields = ['username', 'password', 'password2', 'email',
        'first_name','last_name','address','city','state','zipcode',
        'phone1','phone2',]
    help_texts = {
        'password': 'Must be at least 8 characters.',
    }


def clean_username(self):
    username = self.cleaned_data['username']
    try:
        CommonUser.objects.get(username=username)
    except CommonUser.DoesNotExist:
        return username
    raise forms.ValidationError(self.error_messages['duplicate_username'])


class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm
    fieldsets = UserAdmin.fieldsets + (
        ('Personal info', {'fields': ('address', 'phone1',)}),
    )

admin.site.register(CommonUser, MyUserAdmin)

(snippet of) model.py

from django.contrib.auth.models import AbstractUser

class CommonUser(AbstractUser):
    "User abstraction for carrying general info."

    WORK_STATES = (
            ('FL', 'FL'),
        )

    address = models.CharField(max_length=50)
    city = models.CharField(max_length=30)
    state = models.CharField(max_length=2, default='FL', choices=WORK_STATES)
    zipcode = models.CharField(max_length=10)
    phone1 = models.CharField(max_length=15)
    phone2 = models.CharField(max_length=15, null=True)
    gets_email_updates = models.BooleanField(default=False)


sources

Extending new user form, in the admin Django Using Django auth UserAdmin for a custom user model https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#a-full-example

解决方案

UserAdmin from django.contrib.auth.admin also sets the "add_fieldsets" attribute, that sets the fields to be shown on the add user view. Since UserAdmin sets this field you need to overwrite it to set your own fields.

Here is an example:

class CustomUserAdmin(UserAdmin):
# ...code here...

    fieldsets = (
        (None, {'fields': ('email',)}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name', 'password1',
                       'password2')}
         ),
    )

Hope this helps!

这篇关于用于创建AbstractUser扩展模型的Django管理表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆