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

Comments

iheitlager (on October 2, 2012):
<p>Another trick is to control this from Admin class instead of the template, by only setting the inline in the change_view</p> <pre>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): # .... </pre>

#

Please login first before commenting.