简体   繁体   中英

Django-taggit how to get all tags

I can get all tags' name one by one like this in template

{% for tag in blog.tags.all %}
    <span class="label label-default">{{ tag.name }}</span>
{% endfor %}

And I can get a input from a form like this {{ form.tags }} and it gives me:

<input id="id_tags" name="tags" type="text" value="xxx,y y y,zzz">

However I want to customize my input in my template like this

<input id="id_tags" class="form-control" maxlength="50" name="title" type="text" placeholder="tags" value="{{ form.tags }}">

How to set the input's value=" {{ form.tags }} "?

In your model you can do the following:

  1. First you should have

    tags = TaggableManager(blank = True)

  2. the following will get all the tags and you can use get_tags in a list_field to get all tags for each record.

    def get_tags(self): tags = [] for tag in self.tags.all(): tags.append(str(tag)) return ', '.join(tags)

I'd suggest you'd be better off either using Django's class-based forms (rather than hand-coding the HTML) iff possible, as Taggit already handles this for you.

But to try to answer your question, if you want to get all the tags for a particular object, I think what you need is blog.tags.values_list('name', flat = True) , which means you'll need either to write a custom template tag or - if you're using the word 'blog' to mean 'blog post ' and you're on a single blog post page - you could add the above to the view's context.

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