Python Django替换ModelForm小部件中的选项值
我有一个模型,可以让我在一些预定义的值之间进行选择Python Django替换ModelForm小部件中的选项值,python,django,django-forms,Python,Django,Django Forms,我有一个模型,可以让我在一些预定义的值之间进行选择 in models.py class Customer(models.Model): GENDER = ( ('m' , 'Male') , ('f' , 'Female') ) PersonGender = models.CharField(max_length=20,choices=GENDER) 我有一个模型表单来处理我的表单,这没关系,但我想定义另一个模型表单来更改“性别”值,因为某些原因 我在forms.py中定
in models.py
class Customer(models.Model):
GENDER = ( ('m' , 'Male') , ('f' , 'Female') )
PersonGender = models.CharField(max_length=20,choices=GENDER)
我有一个模型表单来处理我的表单,这没关系,但我想定义另一个模型表单来更改“性别”值,因为某些原因
我在forms.py中定义了另一个ModelForm
GENDER = (('male' , 'Male' ), ('female' , 'Female') )
class MySecondaryForm(forms.ModelForm):
class Meta:
model = Customer
fields = '__all__'
widgets = {
'PersonGender': forms.Select(choices=GENDER)
}
使用此配置下拉菜单,不会更改新值
我可以通过以下配置修复它:
GENDER = (('male' , 'Male' ), ('female' , 'Female') )
class MySecondaryForm(forms.ModelForm):
PersonGender = forms.ChoiceField(choices=GENDER)
class Meta:
model = Customer
fields = '__all__'
使用上面的配置下拉列表值更改我的新设置,但我想知道如何在“widgets”中的元类中更改它 不应在forms.py和model.py中定义性别。只需在models.py中定义它
class MySecondaryForm(forms.ModelForm):
class Meta:
model = Customer
就你的形式而言,已经足够了。在python中,最糟糕的事情就是使用不需要的东西
关于您的评论,这可能是一个选项,如下所述:
http://www.ilian.io/django-forms-choicefield-with-dynamic-values/
引用本文中的代码
def get_my_choices():
# you place some logic here
return choices_list
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_choice_field'] = forms.ChoiceField(
choices=get_my_choices() )
models.py中的GENDER已经定义,我想在forms.py和Meta widgets属性中覆盖它。请参见对答案的修改是的,我知道我可以用“def”方法和我在问题中提到的另一种方法替换这些值,但是我想知道在元类中定义widget的方法,它保留了模型中定义的其他元素,比如required或help文本……这是我唯一知道的方法