Ivan Castellanos
Ivan Castellanos

Reputation: 57

Django hide field from forms and add automatically field

I want to add to the cart the actual product I'm in (product_detail.html). So in the product_unit, is just needed to specify the quantity of the product.

Anyway I can't make the unit_product, automatically add the actual product I'm in.

forms.py

class Product_unitForm(forms.ModelForm):
    class Meta:
        model = Product_unit
        fields = [
            'product',
            'quantity',
        ]

        widgets = {'product': forms.HiddenInput()}

I hide the product from the template, because it is just the actual product, no need to specify.

views.py

def product_detail(request, id_category=None,id_product=None):
   actual_product = Product.objects.get(id = id_product)
   #Has an actual customer
   #FORM
   form_product_unit = Product_unitForm(request.POST or None)

   form_product_unit.fields['product'] = actual_product # I try to add the product this way

   if form_product_unit.is_valid():
       instance_product_unit = form.save(commit=False)
       instance_product_unit.product.save()

   last_order = Order.objects.last()
   is_buying = False
   if(last_order.status == "en curso"):
       is_buying = True

   context = {
       "Product" : actual_product,
       "Is_buying" : is_buying,
       #FORMS
       "form_product_unit" : form_product_unit,
   }
   return render(request, "shopping/product_detail.html", context)

I want to manually from the views, add the product field of product_unit to the actual product it has (actual_product)

template

<img src="{{Product.image.url}}"/>
<h1>{{Product.title}}</h1>

<form method="POST" action="">{% csrf_token %}
{{ form_product_unit.as_p }}

<input type="submit" value="Add" />
</form>

Upvotes: 1

Views: 632

Answers (1)

Paul
Paul

Reputation: 1138

In your views.py file I think you just need to make two changes

def product_detail(request, id_category=None,id_product=None):
   actual_product = Product.objects.get(id = id_product)
   form_product_unit = Product_unitForm(data=request.POST or None,
       initial={'product': actual_product})

And also remove the line form_product_unit.fields['product'] = actual_product. You might need to play around with the initial dictionary a bit to get it to bind the correct value to the field but that's the general idea. The related section in the docs is https://docs.djangoproject.com/en/1.9/ref/forms/api/#dynamic-initial-values

Upvotes: 2

Related Questions