您好我正在尝试使用从我的视图发送的一些其他数据来呈现模型表单。但是当我尝试使用form.as_p
访问表单时,它会出现以下错误:
查询集'对象没有属性'标签'
的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
答案 0 :(得分:2)
您应该将字段的choices
属性设置为标记,您当前正在做的是将字段的值从MultipleChoiceField
更改为QuerySet
以下内容:
self.fields['tags']= self.tags
应该是:
self.fields['tags'].choices = self.tags