2

Every user has (should have) a UserProfile object, and every UserProfile can have Locations against it (foreign key in Location). I want to show these Locations (and allow editing/adding/deleting them) in the User view in the admin site. Nested inlines aren't possible, so I'd like to add a LocationInline to the User page, which I'm unsure how to do.

models.py

from django.db import models
from registration.models import User

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

class Location(models.Model):
    owner = models.ForeignKey(UserProfile)
    # Address and stuff

admin.py

from django.contrib import admin
from django.contrib.auth.models import User
from main.models import UserProfile, Location
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    max_num = 1
    can_delete = False

class LocationInline(admin.TabularInline):
    model = Location
    extra = 1

class UserAdmin(AuthUserAdmin):
    inlines = [UserProfileInline, LocationInline]
    # Obviously doesn't work, because Location is from UserProfile, not User
    # How can I make it use user.profile instead?

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Leagsaidh Gordon
  • 1,641
  • 5
  • 19
  • 28
  • http://stackoverflow.com/questions/2470285/foreign-keys-in-django-admin-list-display – sfletche Apr 28 '14 at 22:55
  • @sfletche Thanks for the link, but that question is asking about a foreign key on the model he is viewing. I have a foreign key going the other way, and is on a field of the model I'm looking at, not the model itself. – Leagsaidh Gordon Apr 29 '14 at 01:13
  • Did you ever found a working solution for this? I'm trying to do something similar and haven't found a working example yet. – Sebastiaan M Nov 22 '15 at 06:14
  • @SebastiaanM: Have you seen [How to Add User Profile To Django Admin](https://simpleisbetterthancomplex.com/tutorial/2016/11/23/how-to-add-user-profile-to-django-admin.html)? It's a `User` `Profile` example using the `OneToOneField` – Jheasly Aug 08 '17 at 21:14

0 Answers0