guettli
guettli

Reputation: 27987

Django Admin Reverse Relations

If you are on the django admin page for the model Group. You don't know that there is a reverse relation to user.

Some people (not me) have difficulties with it.

Is there a way to show all reverse relations, so that you can jump to the matching admin pages?

Example:

On admin page for Group I want a link to User (and all other models which refer to it).

This should happen by code, not by hand with templates.

Upvotes: 5

Views: 1187

Answers (2)

gitaarik
gitaarik

Reputation: 46350

You might also be interested in this extension I created for Django admin pages to link to related objects:

https://github.com/gitaarik/django-admin-relation-links

It's quite easy to use and makes the admin a lot more convenient to use :).

Upvotes: 1

gitaarik
gitaarik

Reputation: 46350

This method doesn't automatically add links to all related models of a Group, but does for all Users related to a Group (so for one related model at a time). With this you'll get an inline view in your Group with the related Users.

You could probably extend this technique to make it automatically work for all related fields.

class UserInline(admin.StackedInline):

    model = User
    extra = 0
    readonly_fields = ('change',)

    def change(self, instance):

        if instance.id:

            # Django's admin URLs are automatically constructed
            # based on your Django app and model's name.
            change_url = urlresolvers.reverse(
                'admin:djangoapp_usermodel_change', args=(instance.id,)
            )

            return '<a class="changelink" href="{}">Change</a>'.format(change_url)

        else:
            return 'Save the group first before editing the user.'

    change.allow_tags = True


class GroupAdmin(admin.ModelAdmin):
    list_display = ('name',)
    inlines = (UserInline,)

Upvotes: 2

Related Questions