Home > database >  Show posts when clicking on a tag (django)
Show posts when clicking on a tag (django)

Time:01-30

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.

CodePudding user response:

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 %}

CodePudding user response:

You can retrieve the posts with:

def post_tag (request, tags):
    posts = Post.objects.filter(tags__tag_slug=tags)
    return render (request, 'blog/post-tags.html', {'posts': posts})

Here posts is a QuerySet with all the Posts that have a tag with as tag_slug the tags URL parameter.

  •  Tags:  
  • Related