Django multiselect choice AttributeError:' str'对象没有属性' status_code'

时间:2013-11-28 21:25:32

标签: django django-forms multi-select multichoiceitems

我已经在models.py中定义了一个类别的选项,这个类别在forms.py中引用,如下所示:

models.py

class Exp(models.Model):
    CATEGORIES = ( ('Inc', 'Inc'),\
                   ('Hom', 'Hom'),\
                   ('syn', 'Syn'),\
                   ('Was', 'Was')\
                 )

forms.py

class ExpForm(ModelForm):
    category = forms.MultipleChoiceField(choices=Exp.CATEGORIES, widget=forms.CheckboxSelectMultiple())
    class Meta:
        model = Exp

views.py

def view_exp(request):
    if request.method == "POST":
        form = ExpForm(request.POST)
        if form.is_valid():
        ...

多选选项在表单中正确显示,但是当我选择多个选项时,form.is_valid()中的views.py将返回false并显示AttributeError: 'str' object has no attribute 'status_code错误。我知道我收到str而不是HttpResponse对象,但无法弄清楚如何修复此错误。任何帮助表示赞赏。

注意:同一表单中还有其他类型为CharField的字段。

这是追溯:

Traceback (most recent call last):
  File "/software/python/python-2.7.3/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response
    response = middleware_method(request, response)
  File "/software/python/python-2.7.3/lib/python2.7/site-packages/django/middleware/common.py", line 106, in process_response
    if response.status_code == 404:
AttributeError: 'str' object has no attribute 'status_code'

1 个答案:

答案 0 :(得分:0)

感谢您的宝贵意见和早上喝咖啡,我深入了解了我的代码。修复错误后,我得到了它的工作。这是我在models.py中的错误:

class Exp(models.Model):

    # The first element in each tuple is the actual value to be stored. The second element is the human-readable name for the option.
    CATEGORIES = ( ('Inc', 'Inc'),\
                 ('Clv','Clv'), \
                 ('Dys', 'Dys'), \
                 ('Hom', 'Hom'), \
                 ('Syn','Syn') )

    #category = models.CharField(max_length=100, choices=CATEGORIES) <--- culprit

我没有意识到我对类别的原始定义仍然挥之不去。我在models.py中评论说它按预期工作了!

这是我的forms.py:

class ExpForm(ModelForm):
    category = forms.MultipleChoiceField(choices=Exp.CATEGORIES,widget=forms.CheckboxSelectMultiple())
    class Meta:
        model = Exp

这是我的views.py:

def view_experiment(request):
    if request.method == "POST":

        form = ExpForm(request.POST)
        if form.is_valid():
            picked = form.cleaned_data.get('category')
            category = ",".join([str(c) for c in picked])
            return HttpResponse("Multichoiceselect returned {0}".format(category))
        else:
            return "[ERROR] from views: {0}".format(form.errors)
    else:
        form = ExpForm()
    return render(request, 'template.html', {'form': form})

选定的多个选项将作为unicode字符串列表返回。然后我将列表元素转换为字符串并用逗号连接它们。

Also see this