I Want That When User Click On Product That Product Detail is Open

I Want That When User Click On Product That Product Detail Page Of That Produc is Open , But I Encountered AN Error , I Want That Url Comes WIth Percentages
Error:

Page not found (404)
No Product matches the given query.
Request Method:	GET
Request URL:	http://127.0.0.1:300/product/macbook-pro-with-retina-display/
Raised by:	ecomapp.views.ProductDetailView
Using the URLconf defined in ecomproject.urls, Django tried these URL patterns, in this order:

admin/
[name='home']
contactus/ [name='contactus']
checkoutcart/ [name='checkoutcart']
checkoutcomplete/ [name='checkoutcomplete']
checkoutpayment/ [name='checkoutpayment']
checkoutinfo/ [name='checkoutinfo']
faq/ [name='faq']
productlist/ [name='product']
search/ [name='search']
myaccount/ [name='myaccount']
index/ [name='index']
aboutus/ [name='aboutus']
addproducts/ [name='addproducts']
login/ [name='login']
logout/ [name='logout']
signup/ [name='signup']
^product/(?P<product_name>[-\w\s]+)/$ [name='productdetail']
The current path, product/macbook-pro-with-retina-display/, matched the last one.

My Views

class ProductDetailView(TemplateView):
    model = Product
    template_name = 'product_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        encoded_product_name = kwargs['product_name']
        decoded_product_name = unquote(encoded_product_name.replace("-", " "))  # Decode the product name

        product = get_object_or_404(Product, title=decoded_product_name)
        context['product'] = product
        context['featured_products'] = Product.objects.filter(is_featured=True)
        context['parent_categories'] = ParentCategory.objects.all()
        context['categories'] = ChildCategory.objects.all()
        return context

    def product_detail_view(request, product_title):
        # Decode the encoded product title back to the original form
        decoded_product_title = quote(product_title.replace("-", " "))

        # Retrieve the product from the database using the decoded title
        product = get_object_or_404(Product, title=decoded_product_title)
        print(product)
        print(decoded_product_title)

My Template

{% for product in tabletproducts %}
                                <!-- BEGIN item -->
                                <div class="item item-thumbnail">
                                    <a href="{% url 'productdetail' product_name=product.title|slugify  %}" class="item-image">
                                        <img src="{{ product.image.url }}" alt="" />
                                        <div class="discount">{{ product.discount_percentage }}% OFF</div>
                                    </a>
                                    <div class="item-info">
                                        <h4 class="item-title">
                                            <a href="{% url 'productdetail' product_name=product.title|slugify %}">{{ product.title }}</a>
                                        </h4>
                                        <p class="item-desc">{{ product.description }}</p>
                                        <div class="item-price">${{ product.discounted_price }}</div>
                                        <div class="item-discount-price">${{ product.price }}</div>
                                    </div>
                                </div>
                                {% endfor %}

My Models

from django.db import models
from django.utils.text import slugify


class ParentCategory(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name


class ChildCategory(models.Model):
    parent_category = models.ForeignKey(ParentCategory, on_delete=models.CASCADE, related_name='child_categories', null=True, blank=True)
    name = models.CharField(max_length=100)
    description = models.TextField()
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name


class Product(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    category = models.ForeignKey(ChildCategory, on_delete=models.CASCADE, related_name='products', null=True, blank=True)
    is_active = models.BooleanField(default=True)

    is_featured = models.BooleanField(default=True)
    discount_percentage = models.PositiveIntegerField(default=0)
    warranty = models.PositiveIntegerField(default=1)
    image = models.ImageField(upload_to='images/', null=True, blank=True)

    def __str__(self):
        return self.title

    def discounted_price(self):
        discount_amount = (float(self.discount_percentage) / 100) * float(self.price)
        discounted_price = float(self.price) - discount_amount
        return "{:.2f}".format(discounted_price)

    def formatted_price(self):
        return "{:.2f}".format(self.price)



class ProductDescription(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_descriptions', null=True, blank=True)
    title = models.CharField(max_length=100, null=True, blank=True, default='')
    description = models.TextField()
    image = models.ImageField(upload_to='images/', null=True, blank=True)

    def __str__(self):
        return self.description


class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_images', null=True, blank=True)
    image = models.ImageField(upload_to='images/', null=True, blank=True)


class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    subject = models.CharField(max_length=150)
    message = models.TextField(max_length=200)

    def __str__(self):
        return self.name

My Urls

  re_path(r'^product/(?P<product_name>[-\w\s]+)/$', views.ProductDetailView.as_view(),
                          name='productdetail'),

Or I Also Used/
path('product/(<product_name>/', views.ProductDetailView.as_view(),
                          name='productdetail'),

The error message is rather clear here.

It’s not that there are any errors in your code, this is a data / query issue.

You apparently don’t have a Product where the title is "macbook pro with retina display"

I have that product in my database at my backend admin panel and the issue is not only there I am also getting the error at other products as well

Please show the Product having that value.

1 Like

You’re searching for ”macbook pro with retina display”, but your model has ”MacBook Pro with Retina Display”, which is not the same.

I am not searching I am trying to get my data dynamically but I think my URL is creating issue check this please

I did check it.

The problem is that you are searching for data that doesn’t exist - at least not any data that you have shown here.

There is no problem with your url - other than that it doesn’t match what you’re showing as being in your table.

You have:

This is a query, searching for an instance of Product, where the title is the decoded_product_name.

In the example you’ve provided here, decoded_product_name == "macbook pro with retina display"
However, you do not have an instance of Product with that title, and so the call to get_object_or_404 generates the 404 error that you are receiving, as shown in the error message you posted.

So please tell me the solution what can I do? And How can I get my data dynamically from my database backend?

If I were doing this, I’d set up the urls and queries to use the primary keys instead of the product names. Structurally, it’s going to be safer and more robust than trying to use the title field.

How can I change my code now so that It will work properly guide me with the code that I provided to you

The basic steps are:

  • Change your url to accept the primary key as the url parameter instead of the title string.

  • Change the links you’re creating to pass the primary key as the parameter instead of the title.

  • Change the query in the view to query by the primary key and not the title.

I have done this It still not working

If you would like assistance with this, please post your updated code along with an errors you may be receiving.