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

Post New Comment