表单中的ModelChoiceField.Form不会验证queryset是否被覆盖 [英] ModelChoiceField in forms.Form won't validate if queryset is overridden

查看:48
本文介绍了表单中的ModelChoiceField.Form不会验证queryset是否被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django ModelChoiceField,如果覆盖查询集,它将无法验证。

I have a django ModelChoiceField that won't validate if I override the queryset.

class PersonalNote(forms.Form):
    tile    = ModelChoiceField(queryset=Tile.objects.none())
    note    = forms.CharField()

form = PersonalNote()
form.fields['tile'].queryset = Tile.objects.filter(section__xxx=yyy)

The form.is_valid()错误是: 选择一个有效的选择。该选择不是可用的选择之一
如果将 Tile.objects.none()替换为 Tile.objects.all(),它将验证,但从数据库加载的数据过多。我也尝试过:

The form.is_valid() error is: "Select a valid choice. That choice is not one of the available choices". If Tile.objects.none() is replaced with Tile.objects.all() it validates, but loads far too much data from the database. I've also tried:

class PersonalNote(forms.Form):
    tile    = ModelChoiceField(queryset=Tile.objects.none())
    note    = forms.CharField()

    def __init__(self, *args, **kwargs):
        yyy = kwargs.pop('yyy', None)
        super(PersonalNote, self).__init__(*args, **kwargs)
        if yyy:
            self.fields['tile'].queryset = Tile.objects.filter(section__xxx=yyy)

这可能是什么问题?请注意,实际的应用程序还会覆盖标签,但这似乎并不是这里的一个因素:

What might be wrong here? Note the real application also overrides the label, but that does not seem to be a factor here:

class ModelChoiceField2(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        assert isinstance(obj,Tile)
        return obj.child_title()


推荐答案

2小时后,我找到了解决方案。因为在类定义中指定了无查询集,所以当实例化要验证的PersonalNote(request.POST)时,它引用的是空查询集

After 2 hours I found the solution. Because you specified a queryset of none in the class definition, when you instantiate that PersonalNote(request.POST) to be validated it is referenceing a null query set

class PersonalNote(forms.Form):
    tile    = ModelChoiceField(queryset=Tile.objects.none())
    note    = forms.CharField() 

要解决此问题,当您基于POST请求创建表单时,请务必在检查is_valid()之前再次覆盖查询集。 / p>

To fix this, when you create your form based on a POST request be sure to overwrite your queryset AGAIN before you check is_valid()

def some_view_def(request):
    form = PersonalNote(request.POST)
    **form.fields['tile'].queryset = Tile.objects.filter(section__xxx=yyy)**

    if form.is_valid():
         #Do whatever it is

这篇关于表单中的ModelChoiceField.Form不会验证queryset是否被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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