[Fixed]-Indirect inline in Django admin

2👍

You can overwrite the User admin page to display both the Profile and the Property models.

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from myapp.models import *

class ProfileInline(admin.TabularInline):
    model = Profile

class PropertyInline(admin.TabularInline):
    model = Property

class UserAdmin(UserAdmin):
    inlines = (ProfileInline, PropertyInline,)

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

You can also remove any unwanted/unused User properties from being displayed (e.g. Groups or Permissions)

more here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-the-existing-user-model

and here:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example

👤Ben

1👍

class PropertyTabularInline(admin.TabularInline):
    model = Property

    def formfield_for_dbfield(self, field, **kwargs):
        if field.name == 'user':
            # implement your method to get userprofile object from request here.
            user_profile = self.get_object(kwargs['request'], UserProfile)
            kwargs["queryset"] = Property.objects.filter(user=user_profile)
        return super(PropertyInLine, self).formfield_for_dbfield(field, **kwargs)

once this is done, you can add this inline to user UserProfileAdmin like:

class UserProfileAdmin(admin.ModelAdmin):
    inlines = (PropertyTabularInline,)

Haven’t tested it, but that should work.

-1👍

It is achievable by making one change in your models.

Instead of creating OneToOne relationship from UserProfile to User, subclass User creating UserProfile. Code should look like that:

class UserProfile(User):
    # some other fields, no relation to User model

class Property(models.Model):
    user = models.ForeignKey(User)

That will result in creating UserProfile model that have hidden OneToOne relation to User model, it won’t duplicate user model.

After doing that change, your code will work. There are some changes under the hood, like UserProfile no longer have it’s own ID, you can access fields from User inside UserProfile and it’s hard to swap User model using settings.AUTH_USER_MODEL (that will require creating some custom function returning proper type and changing migration by hand) but if this is not a problem for you, it may be good solution.

Leave a comment