Home > OS >  I want to show products by category using the . feature (.filter)
I want to show products by category using the . feature (.filter)

Time:09-30

I am a beginner to Django, I want to show products by category using the .feature (.filter), I tried many times but I couldn't do it I hope someone can help me.

Please write the code with explanation

MODELS:

from django.db import models
        
        # Create your models here.
        
        class Category(models.Model):
            name = models.CharField(max_length=200)
            slug = models.CharField(max_length=200)
        
        
        def __str__(self):
            return self.name
        
        class Product(models.Model):
            Category = models.ForeignKey(Category, on_delete=models.CASCADE)
            name = models.CharField(max_length=200, null=False, blank=False)
            slug = models.CharField(max_length=200, null=False, blank=False)
            description = models.TextField(max_length=350, null=False, blank=False)
            image = models.ImageField( null=False, blank=False)
            quantity = models.IntegerField(null=False, blank=False)
        
        
        def __str__(self):
            return self.name

URLS:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.home, name="home"),
    path('f/<str:slug>', views.fd, name="fd"),
    path('category', views.category, name="category"),
    path('category/<str:slug>', views.categoryslug, name="categoryslug"), 
]

VIEWS:

def home(request):
    context = {
        'Pr': Product.objects.all(),
    }
    return render(request, 'pages/home.html', context)


def fd(request, slug):
    context = {
        'gfd' : Product.objects.get(slug=slug),
    }
    return render(request, 'pages/product.html', context)


    
def category(request):
    context = {
        'Categorys': Category.objects.all(),
    }
    return render(request, 'pages/category.html', context)

Please write the code with explanation

i need to show product by category

CodePudding user response:

If you mean you need an implementation for categoryslug, presumably a page for showing a category and its products, something like

def categoryslug(request, slug):
    category = Category.objects.get(slug=slug)
    context = {
        'category': category,
        'products': category.product_set.all(),
    }
    return render(request, 'pages/products-in-category.html', context)

would be a good bare-bones start.

CodePudding user response:

pages/category.html

{% for cat in Categorys %}
    {{ cat.name }}
    {% for obj in cat.product_set.all %}
        {{ obj.name }}
    {% endfor %}
{% endfor %}
  • Related