简体   繁体   中英

In Django admin, include auth.User as an inline

I've seen lots of questions the other way around, which have something along the following:

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)

What I want to do is the reverse, but I can't seen to get it working. Here's the code I have that isn't working.

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)

How can I make this work so that User is an inline in the admin of SpecialUserType ?

The error that I'm getting is:

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

This makes sense, because the OneToOneField is housed in the SpecialUserType model, obviously and not in User . But how can I get it to reverse on the OneToOneField ?

(I know this might seem an unusual thing to do, but there is a good reason that I want to set up the admin this way and not the other way around.)

Unfortunately it can't be done. I've ran into the problem before myself a few times.

As the error message says, the inline model must have a ForeignKey (or OneToOneField) pointing to the main model.

As others have mentioned, I have found subclassing User very helpful for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM