我希望你能在这里看到我想要做什么,只是我想迭代为 group 发布的值,这些值看起来像 group = 1,3,5 等,并将它们添加到数据库中。组是一个复选框。所以我想使用拆分选项。我收到以下消息......
'QuerySet' 对象没有属性 'split'
所以我的理解是它在我用来填充表单的初始化中,这是一个查询,我需要这个,但在发布后它应该只是一个列表。我做错了什么?
视图.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()
表格.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
)
模板.py
{% for value, text in form.group.field.choices %}
<input type="checkbox" name="group" value="{{ value }}" /> {{text}}<br />
{% endfor %}