Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 452
guettli Avatar asked Oct 21 '22 12:10

guettli


1 Answers

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,)
like image 196
gitaarik Avatar answered Oct 27 '22 10:10

gitaarik