views:

150

answers:

2

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',)
+2  A: 

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)
Daniel Roseman
A: 

The inner Meta class is already processed when the ModelForm class is created through a metaclass, which is BEFORE an instance is created. Doing what you ware trying to do in __init__ will not work like that!
You can access the created field objects in a dictonary self.fields eg. you can do something like self.fields['year'] = forms.MyFormField(...).

lazerscience