Search code examples
djangotags

Show posts when clicking on a tag (django)


I am new to django and I am facing a problem I can't solve.

I'm making a blog and I want to be able to click on a tag and go to a new page which will have all posts with this tag. I already made a page which has the selected tag as a slug in the url, but I don't know how to show all the posts with that tag on this page. My models page:

class Tag(models.Model):
    caption = models.CharField(max_length=30)
    tag_slug = models.SlugField(unique=True, db_index=True, null=True)

class Post(models.Model):
    title = models.CharField(max_length = 150)
    image_name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True, db_index=True)
    tags = models.ManyToManyField(Tag)

My urls page:

urlpatterns = [
    path("", views.starting_page, name = "starting-page"),
    path("posts", views.posts, name = "posts-page"),
    path("posts/<slug:slug>", views.post_detail, name = "posts-detail-page"),
    path("posts/tag/<slug:tags>", views.post_tag, name = "post-tag-page"), 
   
]

and the function I created to render this:

  def post_tag (request, tags):
        identified_tag = get_object_or_404(Tag, tag_slug=tags)
        return render (request, "blog/post-tags.html")

I use this function to render the page but I do't know how to select (and render) all posts (their images to be precise) which have a specific tag.


Solution

  • You should query all posts with specified tag and pass it to the template via context

    def post_tag (request, tags):
        identified_tag = get_object_or_404(Tag, tag_slug=tags)
        posts = Post.objects.filter(tag=identified_tag).all()
        return render(request, "blog/post-tags.html", {"posts": posts})
    

    In your template you can access posts like this

    {% for post in posts %}
      {{ post.title }}
    {% endfor %}