Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indirect inline in Django admin

I have the following models:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

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

I would like to create a TabularInline displaying every Property connected to a particular UserProfile on its Django admin page. The problem here is, of course, that Property does not have a ForeignKey directly to UserProfile, so I cannot simply write

class PropertyTabularInline(admin.TabularInline):
    model = Property

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

How can I easily do what I want?

like image 275
haroba Avatar asked Sep 14 '15 09:09

haroba


2 Answers

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

like image 56
Ben Avatar answered Nov 20 '22 09:11

Ben


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.

like image 1
Ajay Gupta Avatar answered Nov 20 '22 10:11

Ajay Gupta