【问题标题】:How to display django tags in update form (django-taggit)?如何以更新形式显示 django 标签(django-taggit)?
【发布时间】:2020-09-21 07:56:52
【问题描述】:

我在 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',]

【问题讨论】:

    标签: django django-taggit


    【解决方案1】:

    post.tags.all 是一个查询集,因此它不会被评估,因为 django 查询是 lazy 并且您只需获取查询集,因为这会返回一个 数据集(如果需要,可以使用数组) 不是一个值。试试这个:

    <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
    

    【讨论】:

    • 效果很好。谢谢!我不知道你可以在 html 值属性中做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 2017-10-14
    • 1970-01-01
    • 2016-09-14
    • 2011-09-10
    • 1970-01-01
    • 2020-04-22
    相关资源
    最近更新 更多