I want to update the Meta.fields
dynamically. Is it possible to do it from the Form constructor? I tried the following but year
doesn't show up during the form generation. Only name
and title
are displayed.
class Author(models.Model):
name = ...
title = ...
year = ...
class PartialAuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title')
def __init__(self, *args, **kwargs):
self.Meta.fields += ('year',)
Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.
form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
No, that won't work. Meta is parsed by - surprisingly - the metaclass, before you even get to __init__
.
The way to do this is to add the field manually to self.fields
:
def __init__(self, *args, **kwargs):
super(PartialAuthorForm, self).__init__(*args, **kwargs)
self.fields['year'] = forms.CharField(whatever)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With