Django Replace choices value in ModelForm Widget

青春壹個敷衍的年華 提交于 2019-12-25 18:31:07

问题


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" ?


回答1:


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


来源:https://stackoverflow.com/questions/44647930/django-replace-choices-value-in-modelform-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!