gpt4 book ai didi

python - 无法在 __init__ 处向 ModelForm 添加字段

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:25 25 4
gpt4 key购买 nike

我对 ModelForm 有疑问。字段 test1 显示,但 test2- 未显示。使用 base_fields 没有帮助。

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

谢谢。

最佳答案

解决了!

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',]

...

关于python - 无法在 __init__ 处向 ModelForm 添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4939737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com