Issue Passing Size Parameter from JavaScript to Django Backend

44 Views Asked by At

I'm encountering an issue with passing the "size" parameter from my JavaScript function to my Django backend. Here's the relevant code snippet from my Django view:

def get_product(request, slug):
    try:
        product = Product.objects.get(slug=slug)

        if request.GET.get('size'):
            size = request.GET.get('size')
            print(size)

        return render(request, "core/product_detail.html")

    except Exception as e:
        print(e)

And here's the JavaScript function:

function get_correct_price(size) {
    console.log(size);
    window.location.href = window.location.pathname + `?size=${size}`;
}

In my HTML template, I'm calling the JavaScript function with the size parameter:

<button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button>

However, when I click the button, the size parameter doesn't seem to be passed to the backend. I've verified that the JavaScript function is being called, and the size parameter is logged correctly in the console.

Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you!

urls.py:

path("products/",product_list_view,name="product_list"),
path("product/<pid>/",product_detail_view,name="product_detail"),
path("product/<slug>/",get_product,name="product_detail"),

In my models.py:

class Size(models.Model):
    name=models.CharField(max_length=100)
    code= models.CharField(max_length=50,blank=True,null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)

    def __str__(self):
        return self.name
class Product(models.Model):
    pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef")


    user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True)
    cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category")
    vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product")
    color=models.ManyToManyField(Color,blank=True)
    size=models.ManyToManyField(Size,blank=True)


    title=models.CharField(max_length=100,default="Apple")
    image=models.ImageField(upload_to=user_directory_path,default="product.jpg")
    description=RichTextUploadingField(null=True, blank=True,default="This is a product")

    price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99)
    old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99)

    specifications=RichTextUploadingField(null=True, blank=True)


    tags=TaggableManager(blank=True)

    product_status=models.CharField(choices=STATUS, max_length=10,default="In_review")


    status=models.BooleanField(default=True)
    in_stock=models.BooleanField(default=True)
    featured=models.BooleanField(default=False)
    digital=models.BooleanField(default=False)

    sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef")

    date=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(null=True,blank=True)

    class Meta:
        verbose_name_plural="Products"

    def product_image(self):
        return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url))

    def __str__(self):
        return self.title
    def get_percentage(self):
        new_price=((self.old_price-self.price)/self.old_price)*100
        return new_price

In short: I simply want that http://127.0.0.1:8000/product/prdeeffeafaec/?size=15inch from the url it should print 15inch this

1

There are 1 best solutions below

9
Pycm On BEST ANSWER
  1. Make your url names unique.

  2. Make url parameters as below.

path("products/",product_list_view,name="product_list"),
path("product/<int:pid>/",product_detail_view,name="product_detail"),
path("product/<slug:slug>/",get_product,name="get_product")

ref

Make an error page template and show this page on exception

def get_product(request, slug):
    try:
        product = Product.objects.get(slug=slug)

        if request.GET.get('size'):
            size = request.GET.get('size')
            print(size)

        return render(request, "core/product_detail.html")

    except Exception as e:
        print(e) 
        return render(request, "core/error_page.html")
  1. Obviously, you model have no field called slug. So below code wouldn't work. And print(size) won't print. It's because below line doesn't work / generate an error.
product = Product.objects.get(slug=slug)

You can only get objects using fields values in the model. Like below.

product = Product.objects.get(title="product_title")

#or

product = Product.objects.get(id=4)