-1

我在 models.py 中定义了一个类别的选择,它在 forms.py 中被引用,如下所示:

模型.py

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

表格.py

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

视图.py

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

多选选项在表单中正确显示,但是当我选择多个选项时,form.is_valid()inviews.py返回 false 并出现AttributeError: 'str' object has no attribute 'status_code错误。我知道我得到的是 astr而不是一个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'
4

1 回答 1

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 字符串列表返回。然后我将列表元素转换为字符串并用逗号连接它们。

也看到这个

于 2013-11-29T15:17:20.977 回答