Why all the tags not displaying in home.html page?

Viewed 10

So here's the problem, I'm trying to display all the tags on the homepage in a dropdown menu but the tags are not being called in base.html. But when I open the specific post itself, the Dropdown menu displays the tags used in that post. Why is that? Can't the tags used in each post be passed on to all pages? Btw I'm using Django-taggit for it.

My views.py goes like this:

def home(request, tag_slug=None):
     posts = Post.objects.all()
     # tag post
     tag = None
     if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        posts = posts.filter(tags__in=[tag])

     context={
     'posts': posts,     #introduces the content added in Post Class
     'tag':tag,
      }

     return render(request, 'blog/home.html', context)

And my urls.py goes like this:

urlpatterns = [
path('', PostListView.as_view(), name='blog-home'), 
path('tag/<slug:tag_slug>/',views.home, name='post_tag'),
]

My base.html goes like this:

                            <li class="list-group-item list-group-item-light" style="text-align:center">
                            <div class="dropdown">
                                <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                  Tags
                                </button>
                                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    {% for tag in post.tags.all %}
                                    <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}">{{tag.name}}</a>
                                    {% endfor %}
                                </div>
                            </div>
                        </li>
1 Answers

This is intended behaviour, if you want to pass data to every page of your application (dropdown menu, notification, etc..) you need a context processor : https://docs.djangoproject.com/en/4.1/ref/templates/api/

  • Create a context_processors.py into blog_app (or whatever your app is called) folder.

  • Add the following code to that new file:

     def whatever_processor(request):
      posts = Post.objects.all()            
      return {'posts': posts}
    
  • Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py

     TEMPLATE_CONTEXT_PROCESSORS += ("blog_app.context_processors.whatever_processor", )
    

And now you can use {{posts}} in all the templates.

Related