Posted on 2013-11-24 19:39:11+00:00
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:
Looking to use dynamic forms in the admin? Be sure to read the follow up post.
Very nice and useful. Thanks!