Django Dynamic Admin Forms

Posted on Nov. 25, 2013

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

Jacob liamApril 8, 2019, 9:13 a.m.

https://www.allassignmenthelp.com

Reply
phille2Aug. 12, 2015, 10:39 a.m.

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
silviogutierrezAug. 12, 2015, 11:27 a.m.

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 RoyJan. 18, 2017, 3:39 p.m.

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

Reply
silviogutierrezJan. 19, 2017, 3:43 a.m.

That's right!

Reply
Jacob liamApril 8, 2019, 9:14 a.m.
Reply
Party FavorsApril 20, 2019, 11:38 a.m.

Hi buddies, it is great written piece entirely defined, continue the good work constantly. Party Favors

Reply
ErinrookesJune 20, 2019, 7:05 a.m.

Very interesting post excellent writing skill keep sharing about new tech Conservatory Roof Repairs in Ayr.

Reply
Elizabeth CamidgeFeb. 27, 2019, 7:47 a.m.

Dynamic form and shape is given for the success of the businessmen of the field. All the arguments of the form and assignmentgeek is shared for the prisons. The rang is deposed for the vital width of the slots for the citizens in the ambit of the regulation for the humans.

Reply
star19March 7, 2019, 10:12 a.m.

I simply want to tell you that I am new to weblog and definitely liked this blog site. I have been meaning to write something like this on my website and you have given me an idea..
top engineering college in chandigarh
engineering college in punjab
Civil Engineering College in Chandigarh

Reply
MHR WriterMarch 21, 2019, 12:25 p.m.

I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing. MHR Writer

Reply
hijMarch 28, 2019, 11:18 a.m.

Apple products are revered for its quality, precision and great design. SRSG started its operations as Apple technology partners in the year 1997.
Apple reseller ahmedabad
Audio mixers dealers in india
Macpro service center in Kolkata
MacBook pro reseller in delhi
ipad reseller bhubaneswar

Reply
Brandon GregoryMarch 31, 2019, 12:30 p.m.

Often, I do not write https://prowritingpartner.com/boomessays-com-review/ because I feel my offering to Him is woefully inadequate. It is during these times I must visit my childhood and remember giving my father a crayon drawing and his congratulating me on such a fine work of art.

Reply
weblink getfreestuffonlinenow.comApril 16, 2019, 9:22 a.m.

I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. navigate to santaclausgreeting.com

Reply
online shopping pakistanApril 17, 2019, 6:43 a.m.

Since demonetization, a lot of people have moved on to the cashless payment methods using debit and credit cards. online shopping pakistan

Reply
BalloonsApril 20, 2019, 6:45 a.m.

I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful. Balloons

Reply
FiguresApril 22, 2019, 7:33 a.m.

I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Figures

Reply
Micheal liam DawsonApril 22, 2019, 11:19 a.m.

I visit your blog and I see too much intresting things on your blog. people seek and learn many things from there.I hope you will share more post like this in upcoming times.avengers endgame quantum realm jacket

Reply
plushApril 22, 2019, 11:22 a.m.

Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. plush

Reply
toddler toysApril 24, 2019, 8:57 a.m.

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites! toddler toys

Reply
Grab and go play packApril 24, 2019, 12:27 p.m.

Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! Grab and go play pack

Reply
collectible tinsApril 25, 2019, 8:58 a.m.

Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! collectible tins

Reply
ver dragon ballApril 25, 2019, 11:30 a.m.

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work. ver dragon ball

Reply
Kristy MurphyApril 26, 2019, 6:51 a.m.

Really very happy to say, your post is very interesting to read. I don't want to stop myself to say something about it. You’re doing a great job. Keep it up. Assignment Writing Service

Reply
Henry JonesApril 29, 2019, 11:10 a.m.

Admin forms are really good if we talk about dynamic django. Thanks alot for this. Keep up the good work :D dissertation methodology help | dissertation topics | dissertation literature review

Reply
iPhone Repair DubaiMay 1, 2019, 7:20 a.m.

I am impressed by the information that you have on this blog. It shows how well you understand this subject. iPhone Repair Dubai

Reply
Best Tyre Shop in DubaiMay 2, 2019, 7:04 a.m.

This post is good enough to make somebody understand this amazing thing, and I’m sure everyone will appreciate this interesting things. Best Tyre Shop in Dubai

Reply
MelonystubbsMay 7, 2019, 11:16 a.m.

I think it is really good for a website developer who wants to develop admin form on their ramadan dua website.

Reply
Alice in wonderlandMay 4, 2019, 12:16 p.m.

This was really an interesting topic and I kinda agree with what you have mentioned here!Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject. Alice in wonderland

Reply
Intensive Driving CourseMay 6, 2019, 6:33 a.m.

I like the valuable info in your articles. I’ll bookmark your blog and check again here regularly. I” ll learn plenty of new stuff right here! Best of luck for the next! Regards, Intensive Driving Courses

Reply
Kristy MurphyMay 6, 2019, 7:18 a.m.

Looking great work dear, I really appreciated to you on this quality work. Nice post!! these tips may help me in the future.Assignment Writing Services

Reply
trenchless sewer pipe replacementMay 6, 2019, 7:49 a.m.

If you are an exporter or importer wishing to buy heat treated wood pallets, you have come to the right place. trenchless sewer pipe replacement

Reply
ellyandersonMay 7, 2019, 11:13 a.m.

I will be attached this form in my e-commerce website please keep sharing about new tech thanks. way promo code

Reply
NikieMay 10, 2019, 12:06 p.m.

We offer calculated visibility for the design and development of technology platforms through ourintensive research-based approach, consistency in performance, and adept decision-making caliber.
web design in malaysia
digital marketing in malaysia
top seo companies in malaysia

Reply
Stefan CarlMay 11, 2019, 5:30 a.m.

Students assignment help provide affordable help with assignment writing services. Our prices are lower than most of the services and still, our quality matches the most expensive assignment writing companies out there.

Reply
WesleyChapmanMay 11, 2019, 9:40 a.m.

Custom lanyards - Personalized

I was looking for this kind of valuable information. Your article is really helpful for me. Thanks a lot.

Reply
chamniessMay 31, 2019, 12:01 p.m.

Omega Industrial Products, Inc. carries and manufactures Handrails and Stairways designed to meet any adopted omegaindl codes. Steel Handrails and Safety Rails are designed from pipe and structural tubing, constructed from heavy gauge steel to meet OSHA fall-protection requirements.

Reply
khanlassiJune 1, 2019, 11:59 a.m.

This product is formally designed and available in the market through an established network of countrywide distributors. It can be omegaindl bollard-coverfor the optimal protection of personnel, equipment and other amenities in today’s high-risk and high-liability environment.

Reply
DavidJune 10, 2019, 5:57 p.m.

It is really great post and i really enjoy when i am reading this article. Thank you for sharing this great post with us. I am really happy to see this. Saludpulso.com

Reply
Abc assignment helpJune 11, 2019, 8:23 a.m.

ABC Assignment Help is an incomparable online Engineering assignment help company delivering excellent academic assignments, essays, coursework and reports. Through a team of over 3000 subject experts we ensure individual attention to every student making the assignment help experience completely personalized in nature.

Reply
PHP Assignment HelpJune 13, 2019, 12:22 p.m.

Thanks for your help, GreatAssignmentHelp is the proper place for all your PHP Assignment Help. Our educator provide help to both the Masters and Bachelor level students. PHP professionals who working with us have a solid grab of Advanced and basic PHP. In addition, We continue update our professor about the new technology in the field of programming, we continue upload our researched technology blogs, articles, and journals. It assurance that you get the best help and rank nothing less than top. PHP Assignment Help PHP Programming Help

Reply
AlexcorbettJune 20, 2019, 6:48 a.m.

A fantastic Ruqyah blog with a lot of valued info about the accidental and secluded investigators.

Reply

Post New Comment