【问题标题】:ModelChoiceField gives "Select a valid choice" error on submissionModelChoiceField 在提交时给出“选择一个有效的选择”错误
【发布时间】:2016-04-06 00:52:25
【问题描述】:

这是我的简单表格,其中有一个ModelChoiceField

class PropertyFilter(forms.Form):
    type = forms.ModelChoiceField(queryset=Property.objects.order_by().values_list('type', flat=True).distinct(),
                                  empty_label=None)

它允许用户从其中一个选项中进行选择(每个选项都表示为一个字符串)。当我选择一个选项并点击“提交”时 - 它返回:

选择一个有效的选项。该选择不是可用的选项之一 选择。

我的views.py 看起来像这样:

from models import Property
from .forms import PropertyFilter

def index(request):
    if request.method == 'POST':
        form = PropertyFilter(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/')
    else:
        form = PropertyFilter()
        properties = Property.objects.all()
    return render(request, 'index.html',  context=locals())

我做错了什么?

【问题讨论】:

    标签: django django-models django-forms


    【解决方案1】:

    ModelChoiceField的queryset参数不能是values_list,因为它会保存关系,所以django必须使用完整的模型对象,而不是模型对象的某些值。

    如果您想显示自定义选择文本,您应该自己定义一个简单的选择字段,以 django 方式。您可以继承 django 表单 ModelChoiceField 并覆盖 label_from_instance 方法以返回您想要显示的文本:

    class PropertyModelChoiceField(forms.ModelChoiceField):
        def label_from_instance(self, obj):
             return obj.type
    
    class PropertyFilter(forms.Form):
        type = PropertyModelChoiceField(queryset=Property.objects.all())
    

    一些不相关的东西,但最好使用PropertyFilterForm 作为表单名称,这将使您的代码更清晰易读。此外type 是python 中的保留字,因此请尝试使用其他名称作为字段名称,例如property_type

    编辑:

    我认为您(以及我)对您的初衷感到困惑。您需要从选择中选择Property 中的types,而不是Property 对象,因此您需要改用ChoiceField

    class PropertyFilter(forms.Form):
        type_choices = [(i['type'], i['type']) for i in Property.objects.values('type').distinct()]
        type = forms.ChoiceField(choices=type_choices)
    

    【讨论】:

    • 感谢您的回答!您能否解释一下您提供的代码如何与我已有的代码相匹配?
    • 对不起,我不明白,但我已经提供了整个东西。您首先将 django 默认 forms.ModelChoieField 子类化以创建自定义字段,然后您的表单 PropertyFilter 使用我们创建的新字段。
    • 我开始明白 :) 有没有办法选择不同的类型值?
    • 嗯。 Property.objects.distinct() - 返回重复项。我做错了吗?
    • 我认为您对如何定义PropertyFilter 感到困惑。听起来您不能将ModelChoiceField 用于您的领域,但是ChoiceField,因为您没有选择Property 模型对象,您只是选择了types。这有意义吗?
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 2018-04-10
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    相关资源
    最近更新 更多