python 在Django表单提交中处理“No color selected”和“No size selected”消息

sczxawaw  于 2023-10-14  发布在  Python
关注(0)|答案(1)|浏览(95)

我正在做一个Django项目,我有一个表单,允许用户在将产品添加到购物车之前选择颜色和尺寸。然而,当用户提交表单而不进行选择时,我遇到了一个问题。我收到以下消息:“未选择颜色”和“未在终端中选择尺寸”。查看 add_to_cart 函数
home.html

<form method="POST" action="{% url 'add_to_cart' products.id %}">
                <div>
                  <select name="colors" class="border border-gray-200 focus:outline-none ">
                    {% for color in Colors.all %}
                      <option value="{{color.color}}">{{color.color|capfirst}}</option>
                    {% endfor %}
                  </select>
                  <select name="sizes" class="border border-gray-200 focus:outline-none ">
                    {% for size in Sizes.all %}
                      <option value="{{ size.size }}">{{ size.size }}</option>
                    {% endfor %}
                  </select>
                </div>
                </form>

views.py

from django.shortcuts import render,redirect
from .models import *

def home(request):
    product = Product.objects.all()
    sizes = Sizes.objects.all()
    colors = Colors.objects.all()
    return render(request , 'home.html' , {'Product':product  , 'Sizes':sizes , 'Colors':colors})

def add_to_cart(request, product_id):
    product = Product.objects.get(id=product_id)
    cart = request.session.get('cart', [])
    
    if request.method == 'POST':
        selected_color = request.POST.get('colors')
        selected_size = request.POST.get('sizes')
        cart_item = {
            'product_id': product.id,
            'color': selected_color,
            'size': selected_size,
        }
        print(cart_item['product_id'])
        
        if selected_color is not None:
            print(cart_item['color'])
        else:
            print("No color selected")
        
        if selected_size is not None:
            print(cart_item['size'])  
        else:
            print("No size selected")
    cart.append(product.id)
    request.session['cart'] = cart
    return redirect('home')


def view_cart(request):
    # Retrieve the cart from the session or create an empty cart if it doesn't exist
    cart = request.session.get('cart', [])
    # Retrieve the products in the cart based on the product IDs stored in the cart
    cart_products = Product.objects.filter(id__in=cart)
    
    # Calculate the subtotal
    subtotal = sum(product.price for product in cart_products)

    context = {
        'cart': cart_products,
        'subtotal': subtotal,
    }
    return render(request, 'cart.html', context)

def remove_from_cart(request, product_id):
    # Retrieve the cart from the session or create an empty cart if it doesn't exist
    cart = request.session.get('cart', [])

    # Remove the product with the given product_id from the cart
    if product_id in cart:
        cart.remove(product_id)
        request.session['cart'] = cart

    return redirect('cart')

models.py

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='products/')

    def __str__(self):
        return self.name
    
class Sizes(models.Model):
    product = models.ForeignKey(Product , on_delete=models.CASCADE)
    size = models.CharField(max_length=5)
    
    class Meta:
        verbose_name_plural = 'Sizes'
    
    def __str__(self) -> str:
        return str(self.product)
    
    
class Colors(models.Model):
    product = models.ForeignKey(Product , on_delete=models.CASCADE)
    color = models.CharField(max_length=10)
    
    class Meta:
        verbose_name_plural = 'Colors'
    
    def __str__(self) -> str:
        return str(self.product)

问题
终端显示
click here for image
product image
我想要颜色,产品尺寸
感谢大家

ozxc1zmp

ozxc1zmp1#

我认为你可以在html文件中添加一个字段验证(必需的)。

<select name="sizes" class="border border-gray-200 focus:outline-none " required>
     {% for size in Sizes.all %}
         <option value="{{ size.size }}">{{ size.size }}</option>
     {% endfor %}
</select>

相关问题