Login

Admin page without inlines dinamically

Author:
davmuz
Posted:
June 16, 2012
Language:
Python
Version:
1.4
Tags:
admin inlines change_view add_view
Score:
0 (after 0 ratings)

Sometimes the related objects needs that the main object exists in order to edit and save them properly. There are two main solutions: override the ModelAdmin.add_view() view or remove the inlines only from the add view page (and not from the change page). The former requires a lot of coding, the latter it's impossible without patching Django because the inlines are not dynamic.

This simple solution hides the inline formsets only from the add page, and not from the change page. Adding an "if" structure it is possible to choose the inlines to use.

Example use case: when a related inline model have to save a file to a path that needs the ID key of the main model, this solution prevent the user to use the related inline model until the model it's saved.

Tested on Django-1.4, should work since Django-1.2.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
admin.py (a slice)
==================

class PhotoInline(admin.TabularInline):
    # ...

class GalleryAdmin(admin.ModelAdmin):
    inlines = [PhotoInline]
    add_form_template = 'admin/add_without_inlines.html'
    # ...

templates/admin/add_without_inlines.html (full)
===============================================

{% extends "admin/change_form.html" %}

{% block inline_field_sets %}
{% for inline_admin_formset in inline_admin_formsets %}
    {{ inline_admin_formset.formset.management_form }}
{% endfor %}
{% endblock %}

More like this

  1. Keeping filter states after edits (Django 1.4) by rhfung 2 years, 4 months ago
  2. keeping filter states after edits by chronosllc 3 years, 7 months ago
  3. Javascript constraints in admin app and fieldsets to tabs (jquery) by jpic 6 years, 1 month ago
  4. Dynamically change admin widgets at runtime by davisd 5 years ago
  5. Collapsed stacked inlines by Aneon 5 years, 11 months ago

Comments

iheitlager (on October 2, 2012):

Another trick is to control this from Admin class instead of the template, by only setting the inline in the change_view

class ConditionalInlineAdmin(admin.ModelAdmin):
    def __init__(self, *args, **kwargs):
        super(ConditionalInlineAdmin, self).__init__(*args, **kwargs)
        self.original_inlines = self.inline_instances

    def add_view(self, request, form_url='', extra_context=None):
        self.inline_instances = []
        return super(ConditionalInlineAdmin, self).add_view(request, form_url, extra_context)

    def change_view(self, request, object_id, extra_context=None):
        self.inline_instances = self.original_inlines
        return super(ConditionalInlineAdmin, self).change_view(request, object_id, extra_context)

class GalleryAdmin(ConditionalInlineAdmin):
    # ....

#

Please login first before commenting.