Django Dynamic Admin Forms

Posted on 2013-11-25 16:30:00+00:00

You've learned how to create dynamic forms and are using them all over the place. But when you try to use them in the admin create and change forms, things don't work quite right. Let's find out how to use dynamic forms in the Django admin.

First, be sure to quickly review the previous post. It'll get you up to speed. Once you're all caught up, let's define our model in models.py:

1
2
3
4
from django.db import models

class Widget(models.Model):
    name = models.CharField(max_length=200)

Then you define your model form in forms.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django import forms
from models import Widget

class WidgetForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(WidgetForm, self).__init__(*args, **kwargs)
        self.fields['my_extra_field'] = forms.CharField()

    class Meta:
        model = Widget

And you go to admin.py to indicate you want WidgetForm used:

1
2
3
4
5
6
7
from django.contrib import admin
from forms import WidgetForm
from models import Widget

class WidgetFormAdmin(admin.ModelAdmin):
    form = WidgetForm
admin.site.register(Widget, WidgetAdmin)

But your extra field doesn't appear. What's going on?

Learning Django? Subscribe to my Django articles, tips and tutorials.

Due to the internals of Django's admin site, the introspection actually looks at the fields defined by the model, not the form. That means that your additional fields won't actually show up.

So what can we do? You might be tempted to explicitly define it as a field, like so:

1
2
3
class WidgetFormAdmin(admin.ModelAdmin):
    form = WidgetForm
    fields = ['name', 'my_extra_field']

However, this option is validated when starting the application. And since your field is dynamic, you'll get an error. Django thinks you're referencing a field that doesn't exist on the form.

If only there were a way to do this at runtime... Wait, you're in luck, there is. Using get_fieldsets you can do just such a thing1. So we do the following:

1
2
3
4
5
6
7
8
9
class WidgetFormAdmin(admin.ModelAdmin):
    form = WidgetForm

    def get_fieldsets(self, *args, **kwargs):
        return  (
            (None, {
                'fields': ('name', 'my_extra_field'),
            }),
        )

And just like that, your additional field will show up. You may we wondering, what's the use case for something like this? The above example is contrived, essentially hard coding the additional field. But using ModelAdmin and its get_form method, you can return a truly dynamic form that varies based on the request or object being edited. You then reuse this logic to populate the fieldsets as needed.


  1. Up until Django 1.6, there is no get_fields. The latest development version does have this method. Once Django 1.7 is released, you'll be able to use this method instead of get_fieldsets if you want a flat form. 

Tags:Django

Comments

phille22015-08-12 10:39:52+00:00

I can not get this to work in Django 1.7. Are you aware of any changes in 1.7 that would make this stop working? I still get the "

Unknown field(s) (<field>) specified for <class>. Check fields/fieldsets/exclude attributes of class <class>.".</class></class></field>

Reply
silviogutierrez2015-08-12 11:27:23+00:00

I'm not sure, maybe something rewritten in the internals? I haven't had a chance to try this with Django 1.7+.

Reply
Sumit Roy2017-01-18 15:39:45+00:00

so i can dynamically add fields on the basis of the value of a boolean field?

Reply
silviogutierrez2017-01-19 03:43:54+00:00

That's right!

Reply
Eliza Lewis12020-05-26 04:04:24.591486+00:00

I stumbled onto your blog and read a few posts. I like your style of writing. Thanks from Boys names and Girls names.

Reply
maria mith2020-05-26 16:54:46.359086+00:00

Each one of them can avail assignment help from us at uniquely low prices. Our experts guarantee to serve you to provide the assignment helper with referencing style provided in assignment guidelines, such as, Harvard, Oxford, MLA, APA or Chicago. Our assignment help Melbourne experts uses a well- recognized and consistent referencing style. Our service for online Melbourne assignment help allows you to get your work re- evaluated and corrected as many times as you wish.

Reply
vshein0312020-05-28 12:30:03.726677+00:00

href="https://sandbox.zenodo.org/communities/chrissmith/">https://sandbox.zenodo.org/communities/chrissmith/ https://jobs.techdirt.com/employers/421618-it-solution-pte-ltd http://www.webestools.com/profile-153012.html https://architecture-jobs.architizer.com/employers/344524-it-solution-singapore https://www.gwmicro.com/App_Central/Profiles/?profileid=2822 https://www.steinberg.net/forums/memberlist.php?mode=viewprofile&u=159684 https://play.eslgaming.com/player/14418214/ https://www.bizcommunity.com/Profile/ChrisSmith_4/c-379 https://archinect.com/firms/cover/150154043/it-solution-singapore http://www.cruzroja.es/creforumvolint_en/user/profile/65853.page http://ubl.xml.org/blog/chris4297smith http://forum.yealink.com/forum/member.php?action=profile&uid=93681 http://echickenhmr4.dgweb.kr/community/board02/?page=1&method=view&no=198 https://git.laquadrature.net/snippets/1360 https://xoops.ec-cube.net/userinfo.php?uid=253774 https://binarylogic.lighthouseapp.com/projects/18752-authlogic/tickets/183-robe-persun https://ecastats.uneca.org/acsweb/cr/Forum/tabid/863/forumid/12/postid/96428/scope/posts/language/en-US/Default.aspx http://forum.meidoyen.openelement.fr/viewtopic.php?p=46503 http://forums.sentora.org/member.php?action=profile&uid=10600 http://www.community.theturninggate.net/profile.php?id=41465 https://jobs.pv-tech.org/employers/304724-it-solution-singapore https://www.milesplit.com/discussion/158309 https://jobs.motionographer.com/employers/335945-it-solution-singapore http://chrissmith.booklikes.com/post/2017733/why-you-should-hire-singapore-seo-agency https://froont.com/suzzie04/singapore-seo-company http://www.bastis.hostingkunde.de/index.php/Special:AWCforum/st/id189/limit:15,15/ http://colleye.96.lt/members/chrissmith/buddyblog/ https://forum.magic.fr/user/vkaish031 http://forums.ernieball.com/members/44470.html https://nianow.com/node/1677550 http://knsz.prz.edu.pl/forum/member.php?action=profile&uid=197171 https://uberant.com/article/585999-how-digital-marketing-is-beneficial-in-advancing-your-business-in-singapore/ https://journal.unnes.ac.id/nju/index.php/ijcls/comment/view/18713/0/24796 https://zeef.com/profile/chris.smith http://szene.digitalkamera.de/members/chrissmith/default.aspx https://ideas.cms2cms.com/ideas/CMS2CMS-I-5212 https://www.mitchell.com/mgmt/testing/newstest/id/2074/mitchell-announces-strategic-partnership-with-verifacts-for-audit-inspection-services https://ae-dev.utbm.fr/snippets/643 http://www.jah.ne.jp/~uchu/kt2/bbs/komae-021-35.shtml https://dailygram.com/index.php/blog/583962/tips-to-choose-the-best-seo-services-provider-in-singapore/ https://www.debate.org/suzzie04/ http://www.psychologies.ru/forum/post/53966/ http://www.aytoloja.org/jforum/user/profile/41086.page http://forum.xyzprinting.com/viewtopic.php?t=1596&p=4768 https://forums.factorio.com/memberlist.php?mode=viewprofile&u=80806 https://choralnet.org/members/chrissmith/ https://crej.com/members/chris4297smith/ https://pop.wi.pb.edu.pl/forum/showthread.php?tid=1193&pid=1817 https://youtubeukblog.blogspot.com/2011/08/mactaggart-lecture-eric-schmidt-live-on.html http://theguild.informe.com/viewtopic.php?p=51640 http://lronhubbard.bloggportalen.se/BlogPortal/view/BlogDetails?id=178948 http://www.basenotes.net/members/26275409-chrissmith https://www.corejoomla.com/profile/suzzie04.html?view=profile http://aowdbbs.snail.com/en/viewtopic.php?f=8&t=2346&view=print http://community.gtarcade.com/thread/1344269-1-1.html http://jomaweb.blogalia.com/historias/75935 https://softuni.bg/forum/28443/how-to-choose-seo-agency-in-singapore https://medium.com/@hudsonamy41/tips-to-incorporate-a-company-in-singapore-5a8c9f700a27 https://www.behance.net/3ecpasgfdac https://vitacoco.zendesk.com/hc/en-us/community/posts/360048184772-Don-t-overthink-take-the-support-of-assignment-help-for-your-academic-growth https://www.dmca.com/Protection/Status.aspx?ID=126c5076-2457-493a-926b-b37bdd8c528f&refurl=https://www.3ecpa.com.sg/services/corporate-secretarial/ https://us10.campaign-archive.com/?u=ecab2673bf58e969e597f1e9c&id=31884eb880 https://gumroad.com/joshuasmith https://www.prweb.com/releases/2015/08/prweb12903190.htm https://www.glassdoor.com/Overview/Working-at-3E-Accounting-EI_IE2376849.11,24.htm https://www.globenewswire.com/news-release/2015/08/24/762661/10146909/en/3E-Accounting-PLT-Moving-on-the-Fast-Track-Towards-International-Growth.html http://site-2117338-5067-3636.mystrikingly.com/blog/a-quick-guide-to-tax-details-for-company-incorporation-in-singapore

Reply

Post New Comment

We will not expose this.