【问题标题】:QuerySet object has no attribute label DjangoQuerySet 对象没有属性标签 Django
【发布时间】:2015-12-11 07:37:03
【问题描述】:

您好,我正在尝试使用从我的视图发送的一些附加数据来渲染模型表单。但是当我尝试使用form.as_p 访问表单时出现以下错误:

QuerySet' 对象没有属性 'label'

test.html

<form action="." method="post">
    {% csrf_token %}

    {{ form.as_p }}
 <div class="row">
  <div class="col-xs-5">
    {{form.tags}}

view.py

class ScheduledTestView(FormView):

serializer_class = TestShortSerializer

template_name = 'admin/scheduled_test.html'
form_class = ScheduledTestForm
initial = {'tags': Tag.objects.all()}


def form_valid(self, form):
    #some logic here

form.py

class ScheduledTestForm(forms.ModelForm):


    tags = forms.MultipleChoiceField(label='Tags', required=False)

    def __init__(self, *args, **kwargs):
        self.tags = kwargs['initial'].pop('tags', None)
        super(ScheduledTestForm, self).__init__(*args, **kwargs)
        self.fields['tags'] = self.tags

    class Meta:
        model = Test

错误回溯

Exception Type: AttributeError
Exception Value:    
     'QuerySet' object has no attribute 'label'
Exception Location:                   /home/kishan/.virtualenvs/kishan_pal/local/lib/python3.4/site- packages/django/forms/forms.py in __init__, line 526
 Python Executable: /home/kishan/.virtualenvs/kishan_pal/bin/python
 Python Version:    3.4.0

【问题讨论】:

  • 另一种将字段添加到模型表单的方法......从视图中也会有所帮助。

标签: python django django-forms


【解决方案1】:

您应该将字段的 choices 属性设置为标签,您当前正在做的是将字段的 MultipleChoiceField 更改为 QuerySet

所以如下:

self.fields['tags']= self.tags

应该是:

self.fields['tags'].choices = self.tags

【讨论】:

  • 非常感谢!!有效 。现在它说 Tag object is not iterable error
  • @kishan - 你可能想问另一个问题,确保包括你为解决这个问题而尝试/研究过的内容
猜你喜欢
  • 2020-03-25
  • 2020-10-31
  • 1970-01-01
  • 2021-08-05
  • 2017-06-22
  • 2013-05-10
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
相关资源
最近更新 更多