2012-12-12 78 views
1

我試圖用自己的管理員(addchange形式)創建自定義的用戶模型。我想有完全一樣的原始用戶管理中帶剛的addchange形式的附加字段。如何添加字段擴展UserAdmin

有人可以幫忙嗎?

models.py

from django.contrib.auth.models import User 

class MyUser1(User): 
    #add more fields specific to MyUser1 

class MyUser2(User): 
    #add more fields specific to MyUser2 

admin.py

from django.contrib.auth.admin import UserAdmin 

class MyUser1Admin(UserAdmin): 
    # how can I add the "fields specific to MyUser1" both in the add 
    # and the change forms? 

admin.site.register(MyUser1, MyUser1Admin) 


# same for MyUser2 

回答

2

我不得不延長UserCreationForm和UserChangeForm:

admin.py

from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm, UserChangeForm 
from django.contrib.auth.admin import UserAdmin 
from django.contrib import admin 
from django import forms 

class MyUser1CreationForm(UserCreationForm): 
    myuser1_field = forms.CharField() 

    class Meta: 
     model = User 
     fields = ("username", "myuser1_field", "password1", "password2") 

class MyUser1ChangeForm(UserChangeForm): 
    myuser1_field = forms.CharField() 

    class Meta: 
     model = User 

class MyUser1Admin(UserAdmin): 

    form = MyUser1ChangeForm 
    add_form = MyUser1CreationForm 

    fieldsets = (
     (None, {'fields': ('username', 'password')}), 
     (_('Personal info'), {'fields': ('myuser1_field', 'first_name', 'last_name', 'email')}), 
     (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 
             'groups', 'user_permissions')}), 
     (_('Important dates'), {'fields': ('last_login', 'date_joined')}), 
    ) 


    add_fieldsets = (
     (None, { 
      'classes': ('wide',), 
      'fields': ('username', 'myuser1_field', 'password1', 'password2')} 
     ), 
    ) 


admin.site.register(MyUser1, MyUser1Admin) 
+0

說'myuser1_field'是在自定義用戶模型的字段。有沒有一種方法來創建字段使用模型的定義 – surfer190

0
from django.contrib.auth.forms import UserChangeForm 

class MyUser1AdminForm(UserChangeForm): 

    class Meta: 
     model = MyUser1 
+0

我還需要重寫附加形式:一些額外的字段是必需的,他們不是在原來的用戶添加的形式,所以保存時我得到一個IntegrityError。額外的領域不在變化形式。 – jul