我希望你能看到我在这里要做的事情,只是我想迭代发布的组的值,看起来像group = 1,3,5等,并将它们添加到数据库中。 group是一个复选框。所以我想使用split选项。我收到以下信息......
'QuerySet'对象没有属性'split'
所以我的理解是在我用于填充表单的init中,这是一个查询,我需要这个但是在帖子上它应该只是一个列表。我做错了什么?
view.py
form = BatchForm(request.user, request.POST)
# Check we have valid data before saving trying to save.
if form.is_valid():
# Clean all data and add to var data.
data = form.cleaned_data
groups = data['group'].split(",")
for item in form.cleaned_data['group']:
batch = Batch(content=data['content'],
group=Group.objects.get(pk=item),
user=request.user
)
batch.save()
forms.py
class BatchForm(forms.ModelForm):
class Meta:
model = Batch
exclude = ('user', 'group')
def __init__(self, user=None, *args, **kwargs):
super(BatchForm, self).__init__(*args,**kwargs)
if user is not None:
form_choices = Group.objects.for_user(user)
else:
form_choices = Group.objects.all()
self.fields['group'] = forms.ModelMultipleChoiceField(
queryset=form_choices
)
template.py
{% for value, text in form.group.field.choices %}
<input type="checkbox" name="group" value="{{ value }}" /> {{text}}<br />
{% endfor %}
答案 0 :(得分:5)
由于您使用的是已清理的数据且它是ModelMultipleChoice
字段,因此它实际上是queryset
。
尝试这样的事情:
form = BatchForm(request.user, request.POST)
# Check we have valid data before saving trying to save.
if form.is_valid():
# Clean all data and add to var data.
data = form.cleaned_data
for group in data['group']:
batch = Batch(
content=data['content'],
group=group,
user=request.user
)
batch.save()
答案 1 :(得分:1)
if form.is_valid():
# Clean all data and add to var data.
data = form.cleaned_data
groups = [x.group for x in form.cleaned_data['group']]
for item in groups:
batch = Batch(content=data['content'],
group=Group.objects.get(pk=item),
user=request.user
)
batch.save()