Django Admin redirect to associated FK object after saving

I have models Section and Content.
Section consists of many Content items - Content has FK to Section.

I’m using Django Admin for management where I have SectionAdmin, ContentAdmin and ContentInline - see the code below (code was simplified for the purpose of this topic).

There are many types of Content that’s why ContentAdmin shows different fields based on a different type of Content:

  • In a first phase you define basic fields like name and you define type.
  • Then after saving, you can see and define (change) additional fields based on a type - get_fields() is used for that.

There is also ContentInline so I can manage (and sort) the list of Content items for a Section.
ContentInline shows only few basic fields but it has show_change_link = True because the idea is that you define name and type and then you go to the ContentAdmin to fill all others.

I would like that, after saving a Content on a ContentAdmin change page, I am redirected to associated Section.
How could I achieve that ?
For example, is it possible to redirect after clicking on a Save OR to have another Save and go to Section button ? Or is there any better way to achieve this ? (I understand Django Admin has its limit but unfortunately don’t have resources to write my own Admin system atm).


CONTENT_DEFAULT_FIELDS = ['name','type','section','published_at',]

class ContentAdmin(admin.ModelAdmin):
    list_display = ('name','type','section','published_at','preview_url')
    list_display_links = ('name',)
    list_filter = ('type',)
    def get_fields(self, request, obj=None):
        if obj:
            if obj.type == 'hyperlink':
                x = CONTENT_DEFAULT_FIELDS.copy()
                x.remove('type') # type is NOT shown anymore (it was set in 1st step) !!!
                return x
            if obj.type == 'image':
                x = CONTENT_DEFAULT_FIELDS.copy()
                x.remove('type') # type is NOT shown anymore (it was set in 1st step) !!!
                return x
			# ... etc. for all types
            return CONTENT_DEFAULT_FIELDS # DEFAULT FIELDS shown for NEW objects when the type is still NOT SET !!!
    def preview_url(self, obj):
        return format_html('<a href="{0}" class="button" target="_blank">Preview</a>&nbsp;',obj.preview_url)
    preview_url.short_description = 'Preview'

class ContentInline(admin.TabularInline):
    model = Content
    extra = 0
    show_change_link = True
    fields = ('name','type','published_at',)
	readonly_fields = ['type',]

class SectionAdmin(admin.ModelAdmin):
    fields = ['name','published_at','created_at','updated_at']
    list_display = ('name','published_at',)
    list_display_links = ('name',)
    inlines = [ContentInline,]

You can probably override the response_add and response_change methods to examine the objects being added or changed and return a redirect to an appropriate admin page.

1 Like