2

我在 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

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

谢谢!

表格.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',]
4

1 回答 1

6

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
于 2020-06-02T18:45:49.847 回答