Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add field to ModelForm at __init__

I have a problem with ModelForm. Field test1 is displayed, but test2- is not. Playing with base_fields didn't help.

# models.py
class Country(models.Model):
    name = CharField(max_length=100)

# admin.py
class CountryAdminForm(ModelForm):
    test1 = forms.CharField('test1')

    def __init__(self, *args, **kwargs):
        super(CountryAdminForm, self).__init__(*args, **kwargs)
        self.fields['test2'] = forms.CharField('test2')

    class Meta:
        model = Country

class CountryAdmin(admin.ModelAdmin):
    form = CountryAdminForm

admin.site.register(Country, CountryAdmin)

Thank you.

like image 438
ilya b. Avatar asked Dec 06 '22 23:12

ilya b.


2 Answers

Solved!

class CountryAdminForm(ModelForm):
    test1 = forms.CharField('test1')

    def __init__(self, *args, **kwargs):
        super(CountryAdminForm, self).__init__(*args, **kwargs)
        self.fields['test2'] = forms.CharField('test2')
        self.Meta.fields.append('test2')

    class Meta:
        model = Country
        fields = ['name', 'test1',]

...

like image 71
ilya b. Avatar answered Dec 09 '22 14:12

ilya b.


I couldn't use self.Meta.fields.append in Django 1.4, because the fields in question is a tuple. You have to concatenate with self.Meta.fields += ('another_field',) instead, for example.

like image 22
trojjer Avatar answered Dec 09 '22 15:12

trojjer