Jason B
Jason B

Reputation: 365

Django iterate comma-separated list in template

My Django project has a field for "Tags," where users can add tags for their posts. Currently this is stored in a models.CharField(max_length=200) field in my model.

What I'd like to do is have it so that when the post is displayed, each word is printed with its own URL to sort the posts by that particular tag. For example, each post also has a "Category" models.CharField where they can select a category from a dropdown list, which is made into a URL in the post.

For example in my Views.py:

@login_required
def category(request, category):
    thisuser = request.user
    if request.method == "POST":
        category = request.POST['category']
    else:
        category = ''
    following = Follow.objects.filter(follower=thisuser).order_by('-pubdate')
    followers = Follow.objects.filter(who_following=thisuser).order_by('-pubdate')

    posts = Post.objects.filter(category__contains=category)

    args = {'posts': posts, 'thisuser': thisuser, 'following': following, 'followers': followers}
    args.update(csrf(request))

    args['category'] = category

    return render_to_response('lobby.html', args)

and in my template:

<a href="/lobby/posts/category/{{post.category|lower}}/">Category: {{post.category}}</a>

Is there a {% for %} template tag I can use to split the values in the tags field by comma and then render each of them as their own instance? Or would I have to do something else, like make a relational database for Tags (since a post can have multiple tags) and then iterate them all by Post ID?

Upvotes: 0

Views: 3707

Answers (2)

Bigcortex
Bigcortex

Reputation: 155

You should do something like

class Post(models.Model):
    def categories(self):
        return self.category.split(',')

and then

{% for category in post.categories %}

but I strongly advice using a m2m relationship in your case. You can use an app like django-taggit to help you with that.

Upvotes: 1

Sohan Jain
Sohan Jain

Reputation: 2377

Database design-wise, the best option is to have a separate model for Tags. This will let you search/sort/filter by tags more easily.

However, if you need a quick fix, you'll have to push that "split by comma" logic to your view/model, like so:

class Post(models.Model):
    tags = models.CharField(...)

    def split_tags(self):
        return self.tags.split(',')


# in your template:
{% for tag in post.split_tags %} {{ tag }} {% endfor %}

Upvotes: 5

Related Questions