I have a basic application where Users create Groups. These Groups can have multiple tags (by way of django-taggit) and, once posted, are rendered on a home page, sorted newest to oldest.
In my views.py I have two different tag lists that the home page uses: a list of all tags and a list of common tags:
class Home(ListView):
model = Group
template_name = 'home.html'
ordering = ['-posted']
def get_common_tags(self):
# common tags
common_tags = Group.tags.most_common()[:2]
return common_tags
def get_context_data(self, **kwargs):
kwargs['common_tags'] = self.get_common_tags()
return super().get_context_data(**kwargs)
class TagFilter(ListView):
model = Group
template_name = 'home.html'
context_object_name = 'group'
def get_queryset(self):
# all tags
tag_list = Group.objects.filter(tags__slug=self.kwargs.get('tag_slug'))
return tag_list
def get_context_data(self, *args, **kwargs):
tag_list = Group.objects.filter(tags__slug=self.kwargs.get('tag_slug'))
tag_list_is_empty = True
if tag_list.exists():
tag_list_is_empty = False
context = super(TagFilter, self).get_context_data()
context["tag_list_is_empty"] = tag_list_is_empty
return context
The idea is that when you click on a tag, it filters the Group results based on that tag:
{% get_taglist as tags %}
<div>
Filter by tag:
{% for tag in tags %}
<a href="{% url 'search_by_tag' tag.slug %}">#{{tag.name}}</a>
{% endfor %}
</div>
<div>
Common tags:
{% for tag in common_tags %}
<a href="{% url 'search_by_tag' tag.slug %}">#{{tag.name}}</a>
{% endfor %}
</div>
{% if tag_list_is_empty == True %}
<p>Sorry! No group found with this tag</p>
{% endif %}
{% for group in object_list %}
<a href="{% url 'group_detail' group.pk %}">
<h1>{{group.name}}</h1>
<p>{{ group.description|slice:":50"}}...</p>
</a>
{% endfor %}
The issue I'm running into is that my list of common tags is only visible at the base url localhost:8000/. But when you click on a tag that brings you to a url of localhost:8000/tags/slug, the list of common tags disappears.
My first thought was that it was something to do with the fact that common_tags is returned in the Home view explicitly and once the url changes it stops being displayed.
This led me to moving both functions into TagFilter, but then I couldn't access tag_list_is_empty in my template. I'm assuming because you can't have two get_context_data function sin the same view.
I'm just wondering what the best way to go about retaining all these variables and passing them to the template so that both tag lists are displayed no matter the url, and the conditional to see if tag_list_is_empty so that I can display the message
<p>Sorry! No group found with this tag</p>