Reputation: 281
i have a model that let me to choice between some predefined values.
in models.py
class Customer(models.Model):
GENDER = ( ('m' , 'Male') , ('f' , 'Female') )
PersonGender = models.CharField(max_length=20,choices=GENDER)
and i have a ModelForm to handle my form , it's ok , but i want to define another ModelForm To Change "GENDER" values for some reasons.
i define another ModelForm in forms.py
GENDER = (('male' , 'Male' ), ('female' , 'Female') )
class MySecondaryForm(forms.ModelForm):
class Meta:
model = Customer
fields = '__all__'
widgets = {
'PersonGender': forms.Select(choices=GENDER)
}
with this configuration Drop-down menu not changes to new values.
i can fix it with below configuration:
GENDER = (('male' , 'Male' ), ('female' , 'Female') )
class MySecondaryForm(forms.ModelForm):
PersonGender = forms.ChoiceField(choices=GENDER)
class Meta:
model = Customer
fields = '__all__'
with above configuration Drop-down values changes to my new , but i want to know how can i change it inside the Meta Class in "widgets" ?
Upvotes: 2
Views: 3264
Reputation: 1118
You should not define GENDER in forms.py and model.py. Just define it in models.py.
class MySecondaryForm(forms.ModelForm):
class Meta:
model = Customer
is sufficent for your form. Worst thing you can do in python is using things that you dont need.
Regarding to your comment maybe this would be an option as described here :
http://www.ilian.io/django-forms-choicefield-with-dynamic-values/
Quoted code from this article
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() )
Upvotes: 1