如何在表单上显示可用的衣服尺寸?Django

mbjcgjjk  于 2022-12-01  发布在  Go
关注(0)|答案(2)|浏览(132)

我正在Django上开发网上服装店。现在我面临的问题是:我有一个表单,帮助用户添加到他的购物车一些衣服。我需要显示哪些尺寸的这件衣服是可用的。要做到这一点,我需要参考数据库。但如何做到这一点从表单?
models.py:

from django.db import models
from django.urls import reverse
from multiselectfield import MultiSelectField

class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_list_by_category',
                       args=[self.slug])

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.FileField(blank=True, upload_to=get_upload_path)

    SIZE_CHOICES = (('XXS', 'XXS'),
                    ('XS', 'XS'),
                    ('S', 'S'),
                    ('M', 'M'),
                    ('XL', 'XL'),
                    ('XXL', 'XXL'))

    sizes = MultiSelectField(choices=SIZE_CHOICES,
                             max_choices=6,
                             max_length=17)

    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.PositiveIntegerField()
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_detail',
                       args=[self.id, self.slug])

我表单:
forms.py

from django import forms

PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]

class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int)
    update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
    #  size = ??

使用此表单视图:
views.py

def product_detail(request: WSGIRequest, product_id: int, product_slug: str) -> HttpResponse:
    product = get_object_or_404(Product,
                                id=product_id,
                                slug=product_slug,
                                available=True)
    cart_product_form = CartAddProductForm()
    return render(request, 'shop/product/detail.html', {'product': product,
                                                        'cart_product_form': cart_product_form})

产品名称:

{% extends "shop/base.html" %}
<head>
    <meta charset="UTF-8">
    <title>Detail</title>
</head>
<body>
{% block content %}
    <br>
    <b>{{ product.name }} </b> <br>
    <i>{{ product.description }} </i> <br>
    {{ product.price }} <br>
    <img src="{{ product.image.url }}" width="300" height="500"> <br>
    Available sizes: <br>
    {{ product.sizes }}<br>
    <form action="{% url "cart:add_to_cart" product.id %}" method="post">
        {{ cart_product_form }}
        {% csrf_token %}
        <input type="submit" value="Add to cart">
    </form>
{% endblock %}
</body>

我试着创建一个函数,它获取可用的大小并发送到表单:
forms.py

def get_sizes(product: Product):
    return product.sizes

但要做到这一点,我需要从表单中引用产品,我不知道如何做到这一点。

wgeznvg7

wgeznvg71#

把每件衣服按尺码(带数量)来划分怎么样?不同尺码的衣服可以作为不同的产品来处理。

产品

| 识别码|姓名|影像|说明书|标价|一个人。|
| - -|- -|- -|- -|- -|- -|
| 一个|牛仔裤| a.jpg |好牛仔裤|小行星12345|一个人。|

大小

| 识别码|产品标识|大小|数量|一个人。|
| - -|- -|- -|- -|- -|
| 一个|一个|XXX|小行星12345|一个人。|
| 2个|一个|第二十一章|小行星一千二百三十四|一个人。|
| 三个|一个|xl个|一百二十三|一个人。|
如果数量大于0,则该尺寸的衣服可用。

iecba09b

iecba09b2#

我解决办法是:
forms.py

from django import forms
from django.forms import ModelForm
from shop.models import Product

class CartAddProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ['sizes']

    def __init__(self, pk, *args, **kwargs):
        super(CartAddProductForm, self).__init__(*args, **kwargs)
        sizes = tuple(Product.objects.get(pk=pk).sizes)
        sizes_list = []
        for item in sizes:
            sizes_list.append((item, item))
        self.fields['sizes'] = forms.ChoiceField(choices=sizes_list)

当我创建表单时,我将pk:
views.py

product = get_object_or_404(Product,
                            id=product_id,
                            slug=product_slug,
                            available=True)
pk = product.pk
cart_product_form = CartAddProductForm(instance=product, pk=pk)

相关问题