【问题标题】:Wrong error message错误的错误信息
【发布时间】:2015-02-12 14:03:01
【问题描述】:

当我尝试购买一种产品的太多商品时,这就是它的样子: 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))

xxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxx

【问题讨论】:

    标签: django django-1.7


    【解决方案1】:

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

    如果您尝试一次编辑多个对象,则应改用formset

    【讨论】:

    • 是的,我在重复相同的形式。我需要为每个表格添加唯一的 ID 吗?怎么做?请帮我提供代码示例:(
    • 您需要使用表单集而不是我所说的单个表单。 godjango.com/9-forms-part-4-formsets 有一个很好的教程,详细介绍了表单集的使用。
    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 2011-10-05
    • 2017-05-12
    • 2018-07-18
    • 2017-02-19
    • 2011-06-14
    • 2013-05-30
    • 2012-11-02
    相关资源
    最近更新 更多