You can obtain the related Mobiles for a given tag with:

from django.shortcuts import get_object_or_404, render
from .models import Tag, Mobile

def tag_detail(request,slug):
    tag = get_object_or_404(Tag, slug__iexact=slug)
    mobiles = Mobile.objects.filter(tag=tag)
    context = {
        'tag': tag,
        'mobiles': mobiles
    }
    return render(request, 'website_primary_html_pages/tag_detail.html', context)

In the template you render this with:

{% for mobile in mobiles %}
    <!-- render the mobile -->
    {{ mobile.name }}
{% endfor %}

You can also paginate [Django-doc] the mobiles objects with:

from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, render
from .models import Tag, Mobile

def tag_detail(request,slug):
    tag = get_object_or_404(Tag, slug__iexact=slug)
    mobiles = Mobile.objects.filter(tag=tag)
    paginator = Paginator(mobiles, 25)  # &leftarrow 25 objects per page
    page_obj = paginator.get_page(request.GET.get('page'))
    context = {
        'tag': tag,
        'mobiles': mobiles,
        'page_obj': page_obj
    }
    return render(request, 'website_primary_html_pages/tag_detail.html', context)

Then you iterate over the page_obj:

{% for mobile in page_obj %}
    <!-- render the mobile -->
    {{ mobile.name }}
{% endfor %}

The section on Paginating a ListView [Django-doc] contains information on how to render the links to the previous/next page.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top