How can i filter variants (size - color ) when select size product show color product ,who saved in database in django?

yacine amateur in django

welcome everybody I'm about to complete my first project, in webbing I ran into a problem, frankly, that I couldn't solve I simply face a problem when I open the page for a specific product, and select a specific size, the colors do not change according to what is stored in databases according to each size

for example

**product 1**    **size**: s l m xl    **color**: red black yellow
if i save variant for **product 1** as **size**: xl with **color**: red
when i select **size** in product-sidebare.html i can not show just **color** red

that is my code

class Add_Product(models.Model):
    STATUS = (
        ('True', 'True'),
        ('False', 'False'),

    VARIANTS = (
        ('None', 'None'),
        ('Size', 'Size'),
        ('Color', 'Color'),
        ('Size-Color', 'Size-Color'),

    article_author = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, max_length=200, on_delete=models.CASCADE)
    title = models.CharField('العنوان', max_length=9500)
    slug = models.SlugField(max_length=250, allow_unicode=True, unique =True)
    image = models.FileField( upload_to = 'Images', blank=True)
    price = models.DecimalField(max_digits=12, decimal_places=2,default=0)
    variant=models.CharField(max_length=10,choices=VARIANTS, default='None')
    posted_on = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True, auto_now_add=False)
    read = models.PositiveIntegerField(default=0, verbose_name='Vu')
    publish = models.DateTimeField( 
    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Add_Product, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('home:show_product', kwargs={'id', 'slug': self.slug})

class PostImage(models.Model):
    post_images = models.ForeignKey(Add_Product, default=None, on_delete=models.CASCADE)
    images = models.FileField(upload_to = 'images/')
    def __str__(self):
        return self.post_images.title

class Color(models.Model):
    name = models.CharField(max_length=20)
    code = models.CharField(max_length=10, blank=True,null=True)
    def __str__(self):
    def color_tag(self):
        if self.code is not None:
            return mark_safe('<p style="background-color:{}">Color </p>'.format(self.code))
            return ""

class Size(models.Model):
    name = models.CharField(max_length=20)
    code = models.CharField(max_length=10, blank=True,null=True)
    def __str__(self):

class Variants(models.Model):
    title = models.CharField(max_length=100, blank=True,null=True)
    product = models.ForeignKey(Add_Product, on_delete=models.CASCADE)
    color = models.ForeignKey(Color, on_delete=models.CASCADE,blank=True,null=True)
    size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True,null=True)
    quantity = models.IntegerField(default=1)
    price = models.DecimalField(max_digits=12, decimal_places=2,default=0)

    def __str__(self):
        return self.title

def show_product(request, id,slug):

    query = request.GET.get('q')
            # show second article
    post = get_object_or_404(Add_Product, id=id, slug = slug)
    product = Add_Product.objects.get(pk = id)
    related_product = Add_Product.objects.order_by('id')[:4]
    also_like = Add_Product.objects.order_by('id')[:4]
    photos = PostImage.objects.filter(post_images=post)
    context = {
         'product': product,
         'full_name': request.user.username,
         'post': post,
         'photos': photos,
         'related_product': related_product,
         'also_like': also_like,
    if product.variant !="None": # Product have variants
        if request.method == 'POST': #if we select color
            variant_id = request.POST.get('variantid')
            variant = Variants.objects.get(id=variant_id) #selected product by click color radio
            colors = Variants.objects.filter(product_id=id,size_id=variant.size_id )
            sizes = Variants.objects.raw('SELECT * FROM  product_variants  WHERE product_id=%s GROUP BY size_id',[id])
            query += variant.title+' Size:' +str(variant.size) +' Color:' +str(variant.color)
            variants = Variants.objects.filter(product_id=id)
            colors = Variants.objects.filter(product_id=id,size_id=variants[0].size_id )
            sizes = Variants.objects.raw('SELECT * FROM  product_variants  WHERE product_id=%s GROUP BY size_id',[id])
            variant =Variants.objects.get(id=variants[0].id)

        context.update({'sizes': sizes, 'colors': colors,
                        'variant': variant,'query': query
    return render(request, 'home/product-sidebar.html', context)

def ajaxcolor(request):
    data = {}
    if request.POST.get('action') == 'post':
        size_id = request.POST.get('size')
        productid = request.POST.get('productid')
        colors = Variants.objects.filter(product_id=productid, size_id=size_id)
        context = {
            'size_id': size_id,
            'productid': productid,
            'colors': colors,
        data = {'rendered_table': render_to_string('color_list.html', context=context)}
        return JsonResponse(data)
    return JsonResponse(data)


                                $(document).on('change', '#post-form',function(e){
                                        url:'{% url "home:ajaxcolor" %}',
                                            action: 'post'
                                        data_type : 'html',
                                        success: function (data) {
                                        error: function (data) {
                                            alert("Got an error dude " + data);

                                    {% if product.variant == 'Size-Color' %}
                                    <div class="col-md-6"> <!-- Start product global 1 -->
                                        <div class="product-details product-details-sidebar">
                                            <h1 class="product-title">{{product.title}}</h1><!-- End .product-title -->

                                            <div class="ratings-container">
                                                <div class="ratings">
                                                    <div class="ratings-val" style="width: 80%;"></div><!-- End .ratings-val -->
                                                </div><!-- End .ratings -->
                                                <a class="ratings-text" href="#product-review-link" id="review-link">( 2 Reviews )</a>
                                            </div><!-- End .rating-container -->

                                            <div class="product-price">
                                            </div><!-- End .product-price -->

                                            <div class="product-content">
                                                <p>Sed egestas, ante et vulputate volutpat, eros semper est, vitae luctus metus libero eu augue.</p>
                                            </div><!-- End .product-content -->


                                            <div class="details-filter-row details-row-size">
                                                <form method="POST"  id="post-form">
                                                <label for="size">Size:</label>
                                                <input type="hidden" name="productid" id="productid" value="{{ }}">
                                                <div class="select-custom">
                                                    {% csrf_token %}
                                                    <select name="size" id="size" class="form-control">
                                                        {% for rs in sizes %}
                                                        <option {% if variant.size_id == rs.size_id %} selected {% endif %} value="{{ rs.size_id }}">{{ }}</option>
                                                        {% endfor %}

                                                </div><!-- End .select-custom -->

                                                <a href="#" class="size-guide"><i class="icon-th-list"></i>size guide</a>
                                            </div><!-- End .details-filter-row -->

                                             <div class="details-filter-row details-row-size">
                                                <form method="post" action="?q=selectvariant" id="post-color">
                                                 {% csrf_token %}
                                                <div id="appendHere">
                                                <label for="size">Color:</label>
                                                <input type="hidden" name="size" id="size" value="{{ size_id }}">
                                                <div class="select-custom">
                                                    <select name="size" id="size" class="form-control">
                                                        {% for rs in colors %}

                                                        <option type='radio' {% if == %} checked {% endif %} name="variantid" id="variantid" value="{{ }}" onchange="this.form.submit();">{{ }}</option>
                                                        {% endfor %}

                                                </div><!-- End .select-custom -->

                                            </div><!-- End .details-filter-row -->

                                            <div class="product-details-action">
                                                <div class="details-action-col">
                                                    <label for="qty">Qty:</label>
                                                    <div class="product-details-quantity">
                                                        <input type="number" id="qty" class="form-control" value="1" min="1" max="10" step="1" data-decimals="0" required>
                                                    </div><!-- End .product-details-quantity -->

                                                    <a href="#" class="btn-product btn-cart"><span>add to cart</span></a>
                                                </div><!-- End .details-action-col -->

                                                <div class="details-action-wrapper">
                                                    <a href="#" class="btn-product btn-wishlist" title="Wishlist"><span>Add to Wishlist</span></a>
                                                    <a href="#" class="btn-product btn-compare" title="Compare"><span>Add to Compare</span></a>
                                                </div><!-- End .details-action-wrapper -->
                                            </div><!-- End .product-details-action -->

                                            <div class="product-details-footer details-footer-col">
                                                <div class="product-cat">
                                                    <a href="#">Women</a>,
                                                    <a href="#">Dresses</a>,
                                                    <a href="#">Yellow</a>
                                                </div><!-- End .product-cat -->

                                                <div class="social-icons social-icons-sm">
                                                    <span class="social-label">Share:</span>
                                                    <a href="#" class="social-icon" title="Facebook" target="_blank"><i class="icon-facebook-f"></i></a>
                                                    <a href="#" class="social-icon" title="Twitter" target="_blank"><i class="icon-twitter"></i></a>
                                                    <a href="#" class="social-icon" title="Instagram" target="_blank"><i class="icon-instagram"></i></a>
                                                    <a href="#" class="social-icon" title="Pinterest" target="_blank"><i class="icon-pinterest"></i></a>
                                            </div><!-- End .product-details-footer -->
                                        </div><!-- End .product-details -->
                                    </div><!-- col-md-6 End product global 1 -->


<input type="hidden" name="size" id="size" value="{{ size_id }}">
<ul class="color-option" >
    <li><span class="text-uppercase">Color:</span></li>
    {% for rs in colors %}
        <input type="radio" name="variantid" id="variantid" value="{{ }}" onchange="this.form.submit();">
        <li >
            <a href="#" style="background-color:{{ rs.color.code }}; color: #D9D9D9; text-shadow: 1px 1px #000000; width: 70px" >
                {{ rs.color }} ${{ rs.price }}
            <img src="{{ rs.image }}" style="height: 70px">
    {% endfor %}

image of my ecommerce website enter image description here

Back to Top