ModelChoiceField在提交表单时给出无效的选择错误 [英] ModelChoiceField gives an invalid choice error upon form submission
问题描述
我想允许用户删除与特定模型相关的外键列表。
I want to allow the user to delete a list of associated foreignkeys to a particular model.
b
class IceBox(models.Model):
...
class FoodItem(models.Model):
name = models.CharField(...)
icebox = models.ForeignKey(IceBox)
def __unicode__(self):
return self.name
用于选择要删除的多个食品的表单:
The form used to select multiple fooditems to be deleted:
class IceBoxEditForm(forms.Form):
fooditems = forms.ModelChoiceField(queryset=FoodItem.objects.none(), widget=forms.CheckboxSelectMultiple(), empty_label=None)
相应的视图:
def icebox_edit(request, item=None):
# Grab the particular icebox
icebox = get_object_or_404(IceBox, pk=item)
if request.method == "POST":
form = IceBoxEditForm(request.POST)
print request.POST
if form.is_valid():
# Delete should happen
else:
form = IceBoxEditForm()
# Only use the list of fooditems that this icebox holds
form.fields['fooditems'].queryset = icebox.fooditem_set.all()
return render_to_response('icebox_edit.html', {'form':form},context_instance=RequestContext(request))
正确列出与该冰箱相关联的食品的复选框。但是,当我选择某些内容然后提交表单时,我会收到表单错误:
The form correctly lists checkboxes of the fooditems associated with that icebox. However, when I select something and then submit the form, I'll get the form error:
选择一个有效的选择。这个选择不是可用的选择之一。
Select a valid choice. That choice is not one of the available choices.
Django是否还有一些其他自定义验证?
Is there some other custom validation I'm missing that Django expects?
编辑:我已经尝试过这个,但是会出现语法错误:
I have tried this, but it gives a syntax error:
form:
class IceBoxEditForm(forms.Form):
fooditems = forms.ModelChoiceField(queryset=FoodItem.objects.none(), widget=forms.CheckboxSelectMultiple(), empty_label=None)
def __init__(self, *args, **kwargs):
queryset = kwargs.pop('queryset', None)
super(IceBoxEditForm, self).__init__(*args, **kwargs)
if queryset:
self.fields['fooditems'].queryset = queryset
view:
form = IceBoxEditForm(queryset=icebox.fooditem_set.all(), request.POST) # Syntax error!
....
else:
form = IceBoxEditForm(queryset=icebox.fooditem_set.all())
....
推荐答案
您已经更改了GET请求的字段的查询集,但不是一个帖子。因此,当您提交表单时,Django仍然使用原始的查询器,因此您的选择无效。
You've changed the queryset for the field for a GET request, but not for a POST. So when you submit the form, Django is still using the original queryset, so your selection is not valid.
在视图开始时更改它,因此发生对于POST和GET,或者更好地在窗体的 __ init __
方法中。
Either change it at the beginning of the view, so it happens for both POST and GET, or even better do it in the form's __init__
method.
这篇关于ModelChoiceField在提交表单时给出无效的选择错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!