错误的错误消息

时间:2015-02-12 14:03:01

标签: django django-1.7

当我尝试购买一件产品的太多物品时,这就是它的样子: 的 screenshot 怎么解决?谢谢你:))

product_list.py

 {% for product in products %}
        <li>
        <b>{{ product }}</b>
            ({{ product.quantity }} available)

        (price: {{ product.price }})

        <form method="post" action=".">
            {% csrf_token %}
            {{ shop_form.as_p }}
            <input type="hidden" id="{{ product.id }}"  name="product_id"  value={{ product.id }} />
            <input type="submit" value="buy"/>
        </form>
    </li><br>
    {% endfor %}

views.py

def product_list(request):
    products = Product.objects.all()

    if request.method == 'POST':
        product_id = request.POST['product_id']
        shop_form = ShopForm(data=request.POST, request_product_id=request.POST['product_id'])
        if shop_form.is_valid():

            quantity = int(request.POST['quantity'])

            product = Product.objects.get(id=product_id)

            price = int(product.price * quantity)

            request.session['koszyk'][product.name] = product.price
            request.session['koszyk']['cena'] += price



            return redirect('/products')
    else:
        shop_form = ShopForm()

    return render(request,
                  'product_list.html',
                  {'shop_form': shop_form, 'products': products})

forms.py

def __init__(self, *args, **kwargs):
    self.request_product_id = kwargs.pop('request_product_id', None)

    super(ShopForm, self).__init__(*args, **kwargs)

    self.fields['quantity'].widget.attrs['id'] = "id_quantity_{0}".format(
        self.request_product_id
    )

def clean(self):
    q = self.cleaned_data['quantity']
    request_product_id = self.request_product_id
    product_quantity = Product.objects.get(id=request_product_id).quantity

    if int(q) > int(product_quantity):
        message = "we have only "
        raise ValidationError("we have only %s :(" %(product_quantity))

xxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx

1 个答案:

答案 0 :(得分:2)

您正在为不同的产品重复相同的表单,这就是您在所有产品中看到第一个错误消息的原因。

如果您尝试一次编辑多个对象,则应使用formset代替。