简体   繁体   English

如何在表格上显示可用的衣服尺码? Django

[英]how to show avaliable sizes of clothes on the form? Django

I'm developing online clothing store on Django. Now I faced the issue: I have a form which helps user to add to his cart some clothes.我正在 Django 开发在线服装店。现在我遇到了这个问题:我有一个表格可以帮助用户将一些衣服添加到他的购物车中。 I need to show which sizes of this clothes are avaliable.我需要展示这件衣服有哪些尺码可供选择。 To do this, I need to refer to the database.为此,我需要引用数据库。 But how to do it from the form?但是如何从形式上做到呢?

models.py:模型.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])

my form:我的表格:

forms.py 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 = ??

the view which uses this form:使用这种形式的视图:

views.py视图.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})

shop/product/detail.html:商店/产品/细节.html:

{% 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>

I tried to create a function which gets avaliable sizes and send to the form:我试图创建一个 function 获取可用尺寸并发送到表单:

forms.py forms.py

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

But to do this I need to refer to the Product from the form, I don't know how to do it.但是要做到这一点,我需要从表格中引用产品,我不知道该怎么做。

How about dividing each clothes by size(with quantity)?如何将每件衣服按尺寸(数量)划分? Clothes with different size can be treated as different product.不同尺寸的衣服可以视为不同的产品。

product产品

ID ID name名称 image图片 description描述 price价格 ... ...
1 1个 jean a.jpg一个.jpg good jean好牛仔 12345 12345 ... ...

size尺寸

ID ID product_id产品编号 size尺寸 quantity数量 ... ...
1 1个 1 1个 xxxl xxxl 12345 12345 ... ...
2 2个 1 1个 xxl xxl 1234 1234 ... ...
3 3个 1 1个 xl xl 123 123 ... ...

If quantity is greater than 0, that size of clothes is available.如果数量大于 0,则该尺寸的衣服可用。

my solution is:我的解决方案是:

forms.py 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)

when I create the form, I pass the pk:当我创建表单时,我传递了 pk:

views.py视图.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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM