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.
First, we declare our model form:
1 2 3 4 5 6 | |
Now we override the constructor, adding our field:
1 2 3 4 5 6 7 8 | |
And that's it. Somewhere in our app views, we'd use this form like so:
1 2 3 | |
A few notes:
- Notice that we do have to pass the request object to the form constructor.
- 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.
Very nice and useful. Thanks!