how to get variation in a product id

Viewed 29

I'm not getting a return on the color and size, only the product name is coming.
And yes my request.POST['color'] and request.POST['size'] are receiving the values, but in the form of names and not in id.

def add_to_cart(request, product_id):
        product = Product.objects.get(id=product_id)
        variation_list = []
    
        if request.method == "POST":
            color = request.POST['color']
            size = request.POST['size']
            
            try:
                variation = Variation.objects.get(product=product, color__name__exact=color, size__name__exact=size)
                variation_list.append(variation)
            except:
                pass
    
        return HttpResponse(variation_list)

HttpResponse

1 Answers

Because HttpResponse is just going to return Raw text you must explicitly say what you want to show, it can't do full objects and it's probably just doing the Models's __str__ method currently

Example:

o = ''
for i in variation_list:
    s += '{0},{1},{2}\n'.format(i.name, i.color.name, i.size.name)

return HttpResponse(s)

Or you could just render a template, like normal, with just a loop like:

{% for i in variation_list %}
{{i.name}},{{i.color}}, etc
{% endfor %}

Another Possibility, that I personally use a Json:

d = []
for i in variation_list:
    d.append({
        'name': i.name,
        'color': i.color.name,
        'size': i.size.name,
    })
import json
return HttpResponse(json.dumps(d), content_type="application/json")
Related