我正在用taggit编写自定义视图-我想用当前分配给该对象的标签来预填充对象编辑formfield。我想用这种格式来安排格式。
相反,我得到的是['this','format'],即使使用下面的代码,我也会得到包含单引号的列表格式
# Create an empty string, iterate through tags and add each one joined with ','
tags_on_set = ''
for each_tag in set.tags.names():
tags_on_set + ',' + each_tag
print(each_tag)
print(tags_on_set)
# prepopulate field with the results of above:
if set.tags:
set_edit.fields['tags'].widget.attrs['value'] = tags_on_set
以上结果导致将其打印出来:['are','new','tags','the','these']。我可以在formfield中删除这些值,然后添加:'here,are,some,new,tags',即使我试图单独打印每个标签,我也会得到相同的结果,一个列表字符串。基本上,在上面的代码中,'each_tag'== ['are','new','tags','the','these']
我实施不正确吗?
** forms.py
class SetEdit(forms.ModelForm):
class Meta():
model = Set
fields = ('title','tags',)
widgets = {
"title":forms.TextInput(attrs={'class':'borderless textinputclass editable',
'placeholder':''}),
"tags":taggit.TagWidget(attrs={'class':'textinputclass editable',
'placeholder':'',}),
}
labels = {
"title":None,
"tags":None,
}
在views.py上实现标签保存 (我尝试了set.tags.add()并获得了相同的结果,只是得到的是累积标签,而不是预期的标签集)
if request.method == 'POST':
set_edit = SetEdit(data=request.POST,)
item_form = ItemForm(data=request.POST,user=user)
if set_edit.is_valid():
set.title = set_edit.cleaned_data['title']
set.tags.set(str(set_edit.cleaned_data['tags']))
set.save()
return HttpResponseRedirect(reverse('curate:set_detail', kwargs={'slug':set.slug}))