Django在ModelForm小部件中替换选项值 [英] Django Replace choices value in ModelForm Widget

查看:82
本文介绍了Django在ModelForm小部件中替换选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,可以让我在一些预定义的值之间进行选择。

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) 

并且我有一个ModelForm来处理我的表单,没关系,但是我出于某种原因想要定义另一个ModelForm来更改 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.

我在Forms.py中定义了另一个ModelForm

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__'

下拉值更改为new,但我想知道如何在Meta内部进行更改在小工具中上课?

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

推荐答案

您不应在form.py和model.py中定义GENDER。只需在models.py中定义它即可。

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

足以满足您的表单要求。您可以在python中做的最糟糕的事情是使用不需要的东西。

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/

本文引用的代码

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

这篇关于Django在ModelForm小部件中替换选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆