2015-02-12 3 views
0

Вот как это выглядит, когда я пытаюсь купить слишком много элементов одного продукта: 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

ответ

2

Вы повторяете форму той же формы для разных продуктов, поэтому вы видите сообщение об ошибке для первого из них.

Если вы пытаетесь отредактировать сразу несколько объектов, вместо этого вы должны использовать formset.

+0

да им повторение той же формы. мне нужно добавить уникальный идентификатор в каждую форму? как это сделать? пожалуйста, помогите мне с образцом кода :( – aabb

+0

Вам нужно использовать набор форм вместо одной формы, как я уже сказал. На https://godjango.com/9-forms-part-4-formsets/ есть хороший учебник. использование форм. – Selcuk

Смежные вопросы