OiO.lk Blog HTML Django: Unable to display colors of linked products
HTML

Django: Unable to display colors of linked products


I’m having trouble displaying the colors of linked products in my Django template. I have a Product model with a many-to-many relationship with a Color model, and I want to display the colors of the linked products.

Here is my view:

def product_varient_detail_view(request, pid):
    # ...
    colors = []
    linked_colors = []

    if product_variant.color.exists():
        colors = product_variant.color.all()

    if product_variant.color.exists():
        for color in product_variant.color.all():
            for linked_product in color.product_varients.all():
                if linked_product != product_variant:
                    linked_colors.extend(linked_product.color.all())

    context = {
        # ...
        'colors': colors,
        'linked_colors': linked_colors,
    }
    return render(request, "core/product_varient_detail.html", context)

And here is my template:

{% if colors %}
    {% for c in colors %}
        <div class="color__radio">
            <input type="radio" id="color_{{ c.id }}" name="color" 
                   data-image-url="{{ c.image.url }}" 
                   class="color-input" 
                   data-url="{% url 'core:product_varient_detail' c.product_varients.first.pid %}?color={{ c.coid }}">
            <label class="color__radio-label" 
                   for="color_{{ c.id }}" 
                   style="background-color: {{ c.code }};"></label>
        </div>
    {% endfor %}
{% endif %}

{% if linked_colors %}
    {% for c in linked_colors %}
        <div class="color__radio">
            <input type="radio" id="color_{{ c.id }}" name="color" 
                   data-image-url="{{ c.image.url }}" 
                   class="color-input" 
                   data-url="{% url 'core:product_varient_detail' c.product_varients.first.pid %}?color={{ c.coid }}">
            <label class="color__radio-label" 
                   for="color_{{ c.id }}" 
                   style="background-color: {{ c.code }};"></label>
        </div>
    {% endfor %}
{% endif %}

However, the colors of the linked products are not being displayed. I’ve tried debugging the code, but I’m not sure what’s going wrong. Can anyone help me figure out the issue?

Models:


class Color(models.Model):
    # ...
    product_varients = models.ManyToManyField('Product', related_name="color_variants", blank=True)

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")
    color=models.ManyToManyField(Color,blank=True)



You need to sign in to view this answers

Exit mobile version