Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django two ForeignKeys to same model - admin error

Tags:

python

django

I have a Profiles app that has a model called profile, i use that model to extend the django built in user model without subclassing it.

models.py

class BaseProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner',primary_key=True)
    supervisor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='supervisor', null=True, blank=True)

@python_2_unicode_compatible
class Profile(BaseProfile):
    def __str__(self):
        return "{}'s profile". format(self.user)

admin.py

class UserProfileInline(admin.StackedInline):
    model = Profile

class NewUserAdmin(NamedUserAdmin):
    inlines = [UserProfileInline ]

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

admin

the error is

<class 'profiles.admin.UserProfileInline'>: (admin.E202) 'profiles.Profile' has more than one ForeignKey to 'authtools.User'.

obviously i want to select a user to be a supervisor to another user. I think the relationship in the model is OK, the one that's complaining is admins.py file. Any idea ?

like image 836
Hakim Avatar asked Sep 02 '26 12:09

Hakim


1 Answers

You need to use multiple inline admin.

When you have a model with multiple ForeignKeys to the same parent model, you'll need specify the fk_name attribute in your inline admin:

class UserProfileInline(admin.StackedInline):
    model = Profile
    fk_name = "user"

class SupervisorProfileInline(admin.StackedInline):
    model = Profile
    fk_name = "supervisor"

class NewUserAdmin(NamedUserAdmin):
    inlines = [UserProfileInline, SupervisorProfileInline]

Django has some documentation on dealing with this: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#working-with-a-model-with-two-or-more-foreign-keys-to-the-same-parent-model

like image 128
Derek Kwok Avatar answered Sep 05 '26 02:09

Derek Kwok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!