Django在ModelChoiceField上形成了keyerror

时间:2012-04-20 14:37:50

标签: django forms

我有一个用于高级搜索的表单。其中一个字段island_group是一个ModelChoiceField,我为其返回values_list作为查询集(以便只获取每个不同的值一次)。

forms.py:

class SearchForm(forms.Form):
    ...
    island_group = forms.ModelChoiceField(
        required=False,
        queryset=Locality.objects.values_list('islandgroup', flat=True).distinct('islandgroup')
    ...

并且因为这会引发invalid choice行的错误,因为我使用的是值而不是对象,我会覆盖错误:

    def clean(self):
        cleaned_data = super(SearchForm, self).clean()

        if self._errors["island_group"]:
            del self._errors["island_group"]

        return cleaned_data

但是,我一直收到KeyError at /collections/ 'island_group'错误。事实上,由于这些数据是从只读数据库中提取的,我只是希望能够以最小的麻烦将其传递到视图中。

非常感谢任何帮助。此外,这里是追溯:

Traceback:
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/sam/django-projects/datazone/bin/datazone/cdrs/views.py" in cdrs_index
  59.     return render(request, 'cdrs_index.html', context)    
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
  44.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  188.         return t.render(context_instance)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render
  123.             return self._render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render
  57.     return self.nodelist.render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render_node
  757.         return node.render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render
  57.     return self.nodelist.render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render_node
  757.         return node.render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render_node
  757.         return node.render(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  227.                 nodelist.append(node.render(context))
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in render
  792.             output = self.filter_expression.resolve(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in resolve
  510.                 obj = self.var.resolve(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in resolve
  653.             value = self._resolve_lookup(context)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/template/base.py" in _resolve_lookup
  683.                         current = getattr(current, bit)
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/forms/forms.py" in _errors
  415.         return self.form.errors.get(self.name, self.form.error_class())
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  112.             self.full_clean()
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  268.         self._clean_form()
File "/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/django/forms/forms.py" in _clean_form
  296.             self.cleaned_data = self.clean()
File "/home/sam/django-projects/datazone/bin/datazone/cdrs/forms.py" in clean
  113.         if self._errors["island_group"]:

Exception Type: KeyError at /collections/
Exception Value: 'island_group'

1 个答案:

答案 0 :(得分:0)

更新

我想我知道你的异常,它可能看起来像Select a valid choice. That choice is not one of the available choices.对吗? 原因是您传递给Locality.objects.values_list('islandgroup', flat=True).distinct('islandgroup')的{​​{1}}是queryset=而不是ValuesListQuerySetQuerySet实例不包含ValueListQuerySet信息并用作普通列表,这会导致_meta生成不正确的表单选项。就像下面的人为举例

ModelChoiceField

但是,第二个选项的正确值应为用户okm的>>> from django import forms >>> from django.contrib.auth.models import * >>> class F(forms.Form): ... user = forms.ModelChoiceForm(queryset=User.objects.values_list('username', flat=True)) >>> print F().as_p() <p><label for="id_user">User:</label> <select name="user" id="id_user"> <option value="" selected="selected">---------</option> <option value="okm">okm</option> </select></p> ,就像

一样
pk

因此,您需要根据>>> class F(forms.Form): ... user = forms.ModelChoiceForm(queryset=User.objects) >>> print F().as_p() <p><label for="id_user">User:</label> <select name="user" id="id_user"> <option value="" selected="selected">---------</option> <option value="1">okm</option> </select></p> 模型字段的类型更改代码中的island_group =行。

除了上述问题,您的代码很好。因此,当islandgroup中没有其他'island_group'验证错误时,self._errors会引发KeyError。