как установить разные размеры для разных продуктов - PullRequest
0 голосов
/ 21 июня 2020

Я хочу добавить разные размеры для некоторых продуктов.

методом, который я пробовал, не удалось обновить размеры в представлении add_to_cart. Как их обновить?

views.py

    @login_required
    def add_to_cart(request, slug):
        item = get_object_or_404(Item, slug=slug)
        order_item, created = OrderItem.objects.get_or_create(
            item=item,
            user=request.user,
            ordered=False
        )
        if request.method == "POST":
            if len(request.POST.get('sizes_choice')) > 0:
                order_item.selcsize = order_item.selcsize+str(request.POST.get('sizes_choice'))
                order_item.save()
                messages.info(request, "This item is selected with size "+order_item.selcsize)
        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            # check if the order item is in the order
            if order.items.filter(item__slug=item.slug).exists():
                order_item.quantity += 1
                order_item.save()
                #if order_item.selcsize != 'False':
                if len(request.POST.get('sizes_choice')) > 0:
                    order_item.selcsize = order_item.selcsize+str(request.POST.get('sizes_choice'))
                    order_item.save()
                messages.info(request, "This item is selected with size "+order_item.selcsize)
                messages.info(request, "This item quantity was updated.")
                return redirect("core:order-summary")
            else:
                order.items.add(order_item)
                messages.info(request, "This item was added to your cart.")
                return redirect("core:order-summary")
        else:
            ordered_date = timezone.now()
            order = Order.objects.create(
                user=request.user, ordered_date=ordered_date)
            order.items.add(order_item)
            messages.info(request, "This item was added to your cart.")
            return redirect("core:order-summary")

index. html

{% if object.has_size %}
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalPopovers">
              select sizes
            </button>
            <form method="POST" action="core:add-to-cart" >
            {% csrf_token %}
            <div id="exampleModalPopovers" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalPopoversLabel">
              <div class="modal-dialog" role="document">
                <div class="modal-content">
                  <div class="modal-body">
                    <h5>Select a size</h5>
                    {% for size in object.size.sizes_choice %}
                    <div class="custom-control custom-radio">
                        <div class="custom-control custom-radio">
                        <input id="{{ forloop.counter }}"  name="sizes_choice" value="{{ size }}" type="radio" class="custom-control-input" required>
                        <label class="custom-control-label" for="{{ forloop.counter }}">{{ size }}</label>
                      </div>
                    </div>
                    {% endfor %}
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <a href="{{ object.get_add_to_cart_url }}" type="submit" class="btn btn-primary btn-md my-0 p">
                      Add to cart
                      <i class="fas fa-shopping-cart ml-1"></i>
                    </a>
                  </div>
                </div>
              </div>
            </div>
            </form>
            {% endif %}

urls.py

path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'),

1 Ответ

0 голосов
/ 27 июня 2020

Я внес эту правку, и она сработала. views.py

class ItemDetailView(LoginRequiredMixin, DetailView):
    model = Item
    template_name = "product.html"
    def get(self, *args, **kwargs):
        url = self.request.get_full_path()
        lst = url.split("/")
        slug = lst[-2]
        item = Item.objects.get(slug=slug)
        items = Item.objects.filter(category=item.category)[0:4]
        items1 = Item.objects.filter(category=item.category)[5:9]
        reviews = Reviews.objects.filter(item=item)
        context={'object':item,'object_list':items,'object_list1':items1, 'reviewsget':reviews}
        if len(reviews)<1:
            context['comment']="Be first to comment..."
        else:
            context['comment']=''
        return render(self.request,self.template_name,context=context)
    def post(self, *args, **kwargs):
        if self.request.method == 'POST':
            #item = get_object_or_404(Item, slug=slug)
            url = self.request.get_full_path()
            lst = url.split("/")
            slug = lst[-2]
            item = Item.objects.get(slug=slug)
            item.selcsize = self.request.POST.get("sizes_choice")
            item.save()
            try:
                rating = self.request.POST.get("rating")
                text = self.request.POST.get("text")
                try:
                    images = self.request.FILES.get("imgs")
                except:
                    pass
                review = Reviews.objects.create(
                user = self.request.user,
                item = item,
                review=text,)
                try:
                    review.images = images
                    review.rating = str(rating)
                    review.save()
                except:
                    pass
            except:
                pass
            if self.request.POST.get("sizes_choice")!=None:
                messages.info(self.request, "This item is selected with size "+str(item.selcsize))
            items = Item.objects.filter(category=item.category)[0:4]
            items1 = Item.objects.filter(category=item.category)[5:9]
            reviews = Reviews.objects.filter(item=item)
            context={'object':item,'object_list':items,'object_list1':items1, 'reviewsget':reviews}
            if len(reviews)<1:
                context['comment']="Be first to comment..."
            else:
                context['comment']=''
            return render(self.request,self.template_name,context=context)

models.py

class Sizes_class(models.Model):
    sizes_choice = ArrayField(models.CharField(null=True, blank=True,max_length = 5), blank=True, default=list)


class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    tag = models.CharField(max_length=10,blank=True,null=True,default='New')
    discount_price = models.FloatField(blank=True, null=True)
    dis_per = models.FloatField(blank=True, null=True,default=-1)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
    label = models.CharField(choices=LABEL_CHOICES, max_length=1)
    slug = models.SlugField()
    description = models.TextField()
    image = models.ImageField()
    weight = models.FloatField(default=0.5)
    pincode = models.IntegerField(default=123456)
    schargeinc = models.FloatField(blank=True, null=True,default=-1)
    has_size = models.BooleanField(default=False,blank=True, null=True,)
    size = models.ForeignKey(Sizes_class, on_delete=models.CASCADE, null=True, default=False)
    selcsize = models.CharField(default=False,null=True,blank=True,max_length=25)
    
    def __str__(self):
        return self.title
        
    def get_add_cart_wsize_url(self):
        return reverse("core:size", kwargs={
            'slug': self.slug
        })
        
    def get_absolute_url(self):
        return reverse("core:product", kwargs={
            'slug': self.slug
        })

    
    def get_add_to_cart_url(self):
        return reverse("core:add-to-cart", kwargs={
            'slug': self.slug
        })

    def get_remove_from_cart_url(self):
        return reverse("core:remove-from-cart", kwargs={
            'slug': self.slug
        })

И зарегистрируйте эти модели в admin.py

...