【问题标题】:Show only some choices for ModelForm field仅显示 ModelForm 字段的一些选项
【发布时间】:2015-02-02 16:53:22
【问题描述】:

假设我有以下模型

class MyChoiceModel(models.Model):
    mychoices = (('ChoiceA', 'ChoiceA'), ('ChoiceB', 'ChoiceB'))

和下面的ModelForm

class MyChoiceModelForm(forms.ModelForm):
    #...
    class Meta:
        model = MyChoiceModel
        fields = ('mychoices', )

现在,用户可以选择所有类型的选项(ChoiceAChoiceB)。 我现在想要的是不会显示某些选择值。

如何过滤来自mychoices 的可用选项,例如,用户只能选择ChoiceA,而在其他情况下,只能选择ChoiceB

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    有很多方法可以做到这一点:这是我有的一种方法

    def CustomChoiceList():
        # return custom choices
    
    class MyChoiceModelForm(forms.ModelForm):
        class Meta:
            widgets = { 'mychoices': CustomChoiceList() }
    

    如果您需要更多控制或访问模型,请查看创建forms.ModelChoiceField)

    例如:

    class CustomChoices(forms.ModelChoiceField):
        def label_from_instance(self, obj):
            # return some obj.title, or whatever in your object as the label to show
    

    然后在 ModelForm 中

    mychoices = CustomChoices(required=True, queryset=YourModelYouWant.objects.filter(...))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 2018-06-25
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      相关资源
      最近更新 更多