December 2018
Beginner to intermediate
796 pages
19h 54m
English
Every form instance has an attribute called fields, which is a dictionary that holds all the form fields. This can be modified at runtime. Adding or changing the fields can be done during form initialization itself.
For example, if we need to add a checkbox to a user-details form only if a keyword argument named "upgrade" is true upon form initialization, then we can implement it as follows:
class PersonDetailsForm(forms.Form):
name = forms.CharField(max_length=100)
age = forms.IntegerField()
def __init__(self, *args, **kwargs):
upgrade = kwargs.pop("upgrade", False)
super().__init__(*args, **kwargs)
# Show first class option?
if upgrade:
self.fields["first_class"] = forms.BooleanField(
label="Fly First Class?")
Now, we ...
Read now
Unlock full access