2012-04-18 82 views
5

晚上好,在Django中擴展用戶配置文件。管理員創建用戶

我目前正在用Django創建一個站點,並且我用用戶配置文件擴展了用戶。雖然我有一個小問題。這是我的情況:

  1. 我擴展了用戶配置文件以添加自定義字段。
  2. 我將模型添加到用戶管理模型中,所以當我添加用戶時,我可以直接填寫字段以創建配置文件。
  3. 現在,如果我不在這些新的自定義用戶字段中添加ANYING,在用戶添加頁面中,Django Admin不會給我一個錯誤,說這些字段爲空(並且它們不是假設的)
  4. 我希望它在此用戶添加管理頁面中引發錯誤,以便管理員在添加新用戶時必須填寫配置文件。
  5. 所有用戶都將被添加到管理面板中。

這可能嗎?非常感謝!

在admin.py

from django.contrib import admin 
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin 
from django.contrib.auth.models import User 
from accounts.models import UserProfile 


class UserProfileInline(admin.TabularInline): 
    model = UserProfile 


class UserAdmin(DjangoUserAdmin): 
    inlines = [ UserProfileInline,] 


admin.site.unregister(User) 
admin.site.register(User, UserAdmin) 

在model.py

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    employee_number = models.PositiveIntegerField(unique=True) 

    def __unicode__(self): 
     return 'Number' 

回答

5

默認情況下,空行內是允許的,因此沒有進一步的檢查將採取一個空形式。你需要手動覆蓋它:

class UserProfileForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     super(UserProfileForm, self).__init__(*args, **kwargs) 
     if self.instance.pk is None: 
      self.empty_permitted = False # Here 

    class Meta: 
     model = UserProfile 


class UserProfileInline(admin.TabularInline):   
    model = UserProfile        
    form = UserProfileForm 
+0

不錯,它的工作!你介意多說一些代碼嗎?尤其是類Meta:部分!謝謝隊友 – abisson 2012-04-19 02:59:09

+0

另外,如果我只想讓其中一個字段爲empty_permitted = false,那麼語法是什麼?其餘的都是真的? – abisson 2012-04-19 03:42:34

+0

@abisson'empty_permitted'是'BaseForm'接受的未公開的參數:當提交的表單沒有從其初始數據改變,並且它的'empty_permitted'是'True',表單的'full_clean()'不會執行任何進一步驗證。你可以在'django/forms/forms.py'和'django/forms/formsets.py'中檢查'empty_permitted'。如果你想讓其中一個字段不爲空,你可以嘗試爲表單設置'empty_permitted = True',爲其他字段設置'blank = True'。 – okm 2012-04-19 04:17:26

相關問題