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 models.py 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) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse(kwargs={'slug':self.slug}) class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ManyToManyField(SubChildCategory, verbose_name='Select Category') created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name
Go to your urls.py file and craete a url for category products…
urlpatterns = [ re_path(r'^category/(?P<slug>[\w\-]+)$', views.categoryproduct, name="cat_product"), ]
Now open your views.py 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"> <p>{{i.name}}</p> *****your html code here for display product data******* </div> </div> {% endfor %}
[…] How to Display ManyTOMany relationship data in View? […]