Django user authentication part 1

We have learned how to add many to many fields for Django models in article Many to Many relations between category and product. But when we display the many to many field values in Django HTML template page, we find the category ( one product can belong to multiple categories) value can not be displayed use Django template code as per your design requirements. This article will tell you how to get the Django model many to many field values and display it in the HTML template page

your file looks like this…

from django.db import models
class SubChildCategory(models.Model):
    name=models.CharField(max_length=50, default=None)
    slug=models.SlugField(unique=True, max_length=50)
    def __str__(self):
    def get_absolute_url(self):
        return reverse(kwargs={'slug':self.slug})
class Product(models.Model):
    slug=models.SlugField(max_length=225, unique=True)
    subcategory=models.ManyToManyField(SubChildCategory, verbose_name='Select Category')
    def __str__(self):

Go to your file and craete a url for category products…

urlpatterns = [
        re_path(r'^category/(?P<slug>[\w\-]+)$', views.categoryproduct, name="cat_product"),

Now open your file and create product display funcation there, using this function you can display products on your html page in related category

from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator

def categoryproduct(request, slug):
    subcategory = get_object_or_404(SubChildCategory, slug=slug)
    productlist = Product.objects.filter(subcategory=subcategory)
    paginator = Paginator(productlist, 12)
    page_number = request.GET.get('page')
    product = paginator.get_page(page_number)
    template_name = 'templatepath/product-lisy.html'
    context = { 'product': product}
    return render(request, template_name, context)

Now go to your app template forlder and create a product-list.html file, where you can display products…

{% for i in product %}
        <div class="col-xl-3 col-6 col-grid-box">
         <div class="product-box">
         *****your html code here for display product data*******
{% endfor %}

Note: Feel free to ask any Question in the comment section if you have any confusion…



Please enter your comment!
Please enter your name here