Login

Generating an InlineModelAdmin Form on the fly

Author:
timbroder
Posted:
September 11, 2012
Language:
Python
Version:
1.4
Tags:
formset InlineModelAdmin ModelAdmin
Score:
0 (after 0 ratings)

Generate the form for an InlineModelAdmin. Usefull for ajaxing in a change in the Inline

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from django.template import loader, Context
from django.contrib.admin import helpers
from django.db import transaction
from django.contrib import admin
 
comp = Comp.objects.get(id=comp_id)
#get the current site
admin_site = admin.site
compAdmin = CompAdmin(Comp, admin_site)
 
#get all possible inlines for the parent Admin
inline_instances = compAdmin.get_inline_instances(request)
prefixes = {}
 
for FormSet, inline in zip(compAdmin.get_formsets(request, comp), inline_instances):
    #get the inline of interest and generate it's formset
    if isinstance(inline, CompSlideInline):
        prefix = FormSet.get_default_prefix()
        prefixes[prefix] = prefixes.get(prefix, 0) + 1
        if prefixes[prefix] != 1 or not prefix:
            prefix = "%s-%s" % (prefix, prefixes[prefix])
        formset = FormSet(instance=comp, prefix=prefix, queryset=inline.queryset(request))
 
#get possible fieldsets, readonly, and prepopulated information for the parent Admin
fieldsets = list(inline.get_fieldsets(request, comp))
readonly = list(inline.get_readonly_fields(request, comp))
prepopulated = dict(inline.get_prepopulated_fields(request, comp))
 
#generate the inline formset
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
            fieldsets, prepopulated, readonly, model_admin=compAdmin)
 
#render the template
t = loader.get_template('tabular.html')
c = Context({ 'inline_admin_formset': inline_admin_formset })
rendered = t.render(c)

More like this

  1. clean validation for dynamic form fields by leveillej 5 years, 1 month ago
  2. Copy/Paste form generation by dballanc 7 years, 8 months ago
  3. Get default form data by dgouldin 4 years, 4 months ago
  4. HTML5 Placeholder from FormField label by Hillshum 2 years, 8 months ago
  5. Generate a dineromail form in python by grillermo 3 years, 4 months ago

Comments

Please login first before commenting.