简体   繁体   中英

How to display django tags in update form (django-taggit)?

I made a basic blog post app in django and I'm using the django-taggit project ( https://github.com/jazzband/django-taggit ) to create taggable Model objects.However, tags show up as a query set in my update form field:

<QuerySet[<Tag:wow]>

Here is what my html looks like:

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

I know there's a way to loop through the tags when displaying them, but is there a way to loop through them within the form? I'm using a single text field to add tags separated by a comma using this tutorial:

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

I don't have an issue saving tags. My only issue is displaying tags that already exist in an editable field on my update form.

thanks!

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 is a queryset so it does not get evaluated since django queries are lazy and you just get the queryset since this returns a set of data (array if you want) not an value. Try this:

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM