Django Dynamic Forms

Posted on Nov. 24, 2013

Django's forms are powerful and simple to use. In most cases, you'll be declaring your fields explicitly. But sometimes you need dynamic forms, and overriding some class methods will let you do just that. This post will show you what to do.

Let's say you want to dynamically add a field to a model form if the user hasn't provided a first name.

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

First, we declare our model form:

1
2
3
4
5
6
from django import forms
from models import Widget

class WidgetModelForm(forms.ModelForm):
    class Meta:
        model = Widget

Now we override the constructor, adding our field:

1
2
3
4
5
6
7
8
class WidgetModelForm(forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        super(WidgetModelForm, self).__init__(*args, **kwargs)
        if not request.user.first_name:
            self.fields['first_name'] = forms.CharField()

    class Meta:
        model = Widget

And that's it. Somewhere in our app views, we'd use this form like so:

1
2
3
def my_view(self, request):
    form = WidgetModelForm(request, request.POST or None)
    # .. and so on

A few notes:

  1. Notice that we do have to pass the request object to the form constructor.
  2. Since we now have this extra argument, we need to leave it out when calling the parent class' constructor.

Looking to use dynamic forms in the admin? Be sure to read the follow up post.

Tags:Django

Comments

Chris KavanaghFeb. 23, 2016, 1:58 a.m.

Very nice and useful. Thanks!

Reply
Mackenzie MorriceMarch 14, 2019, 5:06 a.m.

Dynamic forums are present in all over the world and use as platform to show your abilities and your work to get success in life. Here is the detail of the writemyessay4me.org in which Django dynamic forums are most helpful to getting the solution of problem and show your ability.

Reply
David MillarApril 6, 2019, 11:33 a.m.

Unity. Besides, the leaders can put it as a subject in their forum. This is a best way to achieve the target. Women Red Quilted Leather Jacket

Reply
Sherita GreenApril 19, 2019, 3:39 p.m.

Dynamic Django models enable clients to characterize alter and populate their own database tables and apply run time pattern changes to the database, Django dynamic models is approximately found on the run time dynamic. Appreciative such an amazing for sharing this radiant data. Bird Box Sarah Paulson Coat

Reply
AnjaliApril 24, 2019, 4:41 a.m.
Reply
dsdsdMay 6, 2019, 5:39 a.m.

Il y a toujours un problème dans le processus de vente, c'est-à-dire que le client a une méfiance vis-à-vis du personnel de vente. Ils pensent que les informations obtenues auprès du personnel de vente de la cartier Montre auront souvent des degrés différents d'exagération et de fausseté, aussi être une fraude. Par conséquent, de nombreux clients pensent que les paroles du vendeur peuvent être entendues ou non dans le processus de communication avec le personnel de vente, ne s'en soucient souvent pas trop et même se disputer avec le personnel de vente avec une psychologie rebelle.breitling Montre

Reply
Mike RooneyMay 14, 2019, 7:26 p.m.

With France. He was one of the few African leaders at the time that was not obsessive in radical ideology and thought. Avengers Endgame Captain America Jacket

Reply
Team ExtremeMay 31, 2019, 6:38 p.m.

I learned a lot form this article. These kinds of articles help me learning Django Dynamic Forms. This website always helps me finding any topic I am interested in. This is a very good website. If you are a fan of Harley Davidson motorbikes, then you must check out our site, Harley Davidson Motorcycles For Sale

Reply
make my assignmentsJune 6, 2019, 5:30 a.m.

Good Inspirational Content. Thanks for telling and changing perception. We provide academic content help services to students who are looking for assignments help for their high school and colleges. Visit : Make my Assignments https://www.makemyassignments.com/au/ https://www.makemyassignments.com/nz/

Reply
sohobiztubeJune 6, 2019, 5:35 a.m.

Thanks for the information you provided. Regards Sohobiztube

https://www.sohobiztube.com

Sohobiztube- Directory Submission

Reply
Find assignment serviceJune 6, 2019, 5:36 a.m.

Nice Post !! Before hiring Someone for Assignments check the comments for them at Find Assignment Services. Find Assignment Services

Reply
My assignment helperJune 6, 2019, 5:50 a.m.

MyAssignmentHelper.co.uk is among the best companies on the online assignment writing market. We offer top-notch essays, Assignments, research papers, thesis and other types of works that can be assigned to you at a high school or college. Check out what we offer, try working with our paper writing service.

My Assignment Helper UK

Reply
Deep sea atlanticnaJune 12, 2019, 5:27 p.m.

The northern red snapper is a species of snapper native to the western Atlantic Ocean including the Gulf of Mexico. We deliver it to your house at the best price in the given time. Visit Red Snapper for more information

Reply
Adam HebrewJune 20, 2019, 12:48 p.m.

Such a nice blog post on this topic. I am Adam Hebrew form Aberdeen, the UK associated with myassignmenthelp.co.uk. My Assignment help has been the leading essay writing service since 2007. Each essay is written by a fully qualified writer who specializes in your chosen subject area. https://myassignmenthelp.co.uk/essay-help/essay-writing-services.html

Reply
john dearJuly 19, 2019, 9:19 a.m.

I have really enjoyed reading your blog posts. Any way I'll be active target promo codes, subscribing to your feed and I hope you post again soon.

Reply
sim 4 updateJuly 20, 2019, 3:56 a.m.

My friend recommended this blog and he was totally right keep up the fantastic work! sims 4 update

Reply
carma tecJuly 30, 2019, 6:39 a.m.

My friend recommended this blog and he was totally right keep up the fantastic work! Ruby on Rails Development Company in India

Reply
best service center marathahalliJuly 30, 2019, 9:45 a.m.

You're so cool! I do not think I've truly read something like this before. So great to find someone with genuine thoughts on this topic. Really.. thank you for starting this up. This site is one thing that is needed on the internet, someone with a bit of originality! Samsung service center marathahalli | oppo service center marathahalli | oneplus service center marathahalli | LG service center marathahalli | realme service center marathahalli | best service center marathahalli

Reply
Mike RooneyJuly 30, 2019, 11:42 a.m.

A bit long for a blog title but the .com version of domain...about when trying to come up with a good title domain name is to. ok pig is not such a nice word to use when it comes to. Top Gun Maverick Jacket

Reply
susan mayerJuly 31, 2019, 6:40 a.m.

I appreciate several from the Information which has been composed, and especially the remarks posted I will visit once more. instagram viewer

Reply
bfndsnAug. 16, 2019, 9:50 a.m.

生完孩子怎么丰胸好三:合理的饮食。坚果类食物丰胸粉嫩公主丰胸产品。比如核桃、花生、杏仁这一类食物,女人要多吃产后丰胸最快方法,坚果中富含维生素E可以让皮肤细腻紧绷而且光滑最有效丰胸产品。多吃黑芝麻有促进卵巢发育、增加雌激素分泌量和刺激乳房发育的作用粉嫩公主酒酿蛋丰胸

Reply

Post New Comment