Home > database >  I have a problem that I could not fetch product details by category
I have a problem that I could not fetch product details by category

Time:10-02

I have a problem that I could not fetch product details by category Because Viwes contains two variables and I couldn't get them to show the product details

Model

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

path('category/<str:product_category_slug>/<str:product_slug>/', views.product_detail, name="product-detail")

Viwes

def product_detail(request, product_category_slug=None, product_slug=None):
    #How do I get product details through this path that contains a category and then the product

I hope someone can help me

CodePudding user response:

def product_detail(request, product_category_slug, product_slug):
    product = Product.objects.get(slug=product_slug, Category__slug=product_category_slug)
    if product:
       return product
    else: 
       return "Product not found"

I hope this will return the Project object with the category. to get Category details lets say you want to get category name and its slug you can just do the following: category name will product.Category.name and slug will be product.Category.slug

CodePudding user response:

You can do it this way

def get_product_details(request, category_slug, slug):
    # Change <Category> field name to <category> 
    product = get_object_or_404(Product, category__slug=category_slug, slug=slug)
    context = dict(product=product)
    return response(response, "product_detail.html", context)

or this way:

def get_product_details(request, category_slug, slug):
     try:
          product = Product._default_manager.get(category__slug=category_slug, slug=slug)
     except Product.DoesNotExist:
          product = None
    context = dict(product=product)
    template_name = "product_404_template.html" if product is None else "product_detail.html"
    return response(response, template_name, context)

You still need to 404 for both cases.

  • Related