Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you update a Django Form Meta class fields dynamically from the form constructor?

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',)
like image 714
Thierry Lam Avatar asked Jun 14 '10 16:06

Thierry Lam


People also ask

What is class Meta in Django form?

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.

What is form Is_valid () in Django?

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.

What is the difference between form and ModelForm in Django?

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.

What is form Cleaned_data in Django?

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).


1 Answers

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)
like image 121
Daniel Roseman Avatar answered Sep 22 '22 23:09

Daniel Roseman