aabb
aabb

Reputation: 79

Wrong error message

This is how it looks when i try to buy too many items of one product: screenshot How to fix it? thank you:)

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

Upvotes: 0

Views: 27

Answers (1)

Selcuk
Selcuk

Reputation: 59184

You are repeating the same form for different products, that's why you are seeing the error message for the first one in all of them.

If you are trying to edit multiple objects at once, you should use a formset instead.

Upvotes: 2

Related Questions