如何在更新表单中显示 django 标签(django-taggit)?



我在django中制作了一个基本的博客文章应用程序,我正在使用django-taggit项目(https://github.com/jazzband/django-taggit(来创建可标记的模型对象。但是,标签在我的更新表单字段中显示为查询集:

<QuerySet[<Tag:wow]>

这是我的 html 的样子:

<input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{{ post.tags.all }}">

我知道有一种方法可以在显示标签时循环浏览标签,但是有没有办法在表单中循环浏览它们?我使用单个文本字段添加用逗号分隔的标签,使用本教程:

https://dev.to/coderasha/how-to-add-tags-to-your-models-in-django-django-packages-series-1-3704

我在保存标签时没有问题。我唯一的问题是显示更新表单上可编辑字段中已存在的标签。

谢谢!

forms.py:

from taggit.forms import TagWidget
class PostForm(ModelForm):
class Meta:
model = Post
widgets = {'content_text': forms.Textarea(attrs={'cols': 80, 'rows': 80}),
'tags': TagWidget(),
} 
fields = ['title', 'video_URL', 'content_text', 'score', 'tags',]
post.tags.all

是一个查询集,所以它不会被评估,因为 Django 查询是懒惰的,你只得到查询集,因为它返回一组数据(如果需要,数组(而不是值。试试这个:

<input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{% for tag in post.tags.all %}{{ tag }},{% endfor %}">
# I used a comma to separate them but feel free to use whatever you want

最新更新