Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 761
jdotjdot Avatar asked Oct 18 '12 16:10

jdotjdot


1 Answers

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
like image 186
Collin Anderson Avatar answered Oct 26 '22 18:10

Collin Anderson