2012-10-18 11 views
6

我見過很多的問題,周圍的其他方法,它具有沿下面的內容:在Django管理,包括auth.User作爲內嵌

class UserProfileInline(admin.StackedInline): 
    model = UserProfile 
    can_delete = False 
    verbose_name_plural = 'profile' 

class NewUserAdmin(UserAdmin): 
    inlines = (UserProfileInline,) 

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

我想要做的是相反的,但我看不到它的工作。這是我沒有工作的代碼。

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

class UserInline(admin.StackedInline): 
    model = User 
    can_delete = False 

class IncludeUserAdmin(admin.ModelAdmin): 
    inlines = (UserInline,) 

admin.register(SpecialUserType, IncludeUserAdmin) 

我怎樣才能使這項工作,使User是在SpecialUserType管理員內嵌?

是我得到的錯誤是:

<class 'django.contrib.auth.models.User'> has no ForeignKey to <class 'students.models.SpecialUserType'> 

這是有道理的,因爲OneToOneField收納在SpecialUserType模型,顯然而不是在User。但是我怎樣才能讓它在OneToOneField上逆轉呢?

(我知道這可能看起來不尋常的事情,但我想設置管理員這種方式,而不是周圍的其他方式一個很好的理由。)

+0

什麼版本的Django您使用的是? – sepulchered

+0

爲了將用戶模型添加到缺失的關係中,你不會爲你工作嗎? – Ambroise

回答

1

不幸的是它不能完成。我在幾次之前就遇到了這個問題。

如錯誤消息所示,內聯模型必須具有指向主模型的ForeignKey(或OneToOneField)。

正如其他人所說,我已經找到了子類的用戶我非常有幫助:

class UserProfile(User): 
    user = OneToOneField(User, parent_link=True) 
    # more fields, etc 
+0

當最初提出這個問題時,子類'User'不是一個選項。幸運的是,現在是。 – jdotjdot

+0

信不信由你,但自2010年3月以來我一直在繼承用戶,只是沒有AUTH_USER_MODEL。 –