0

I have a product model, which i have the modelforms to make a form for and then implemented in my views and templates. After submitting the form, the product is not being added to the database and I don't know what the error seems to be.

I made sure to use the enctype="multipart/form-data" because of the image field in the form and also request.FILES.

N.B:I am getting Error Adding Product which is the else statement if the form is not valid, but i don't know how the form is not valid.

models.py

class Product(models.Model):
    name = models.CharField(max_length=36)
    price = models.PositiveIntegerField()
    description = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField()
    image = models.ImageField(upload_to='images/products', default='images/products/default-product.jpeg', blank=True, null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True)
    country = CountryField(blank_label='(select country)')

    def __str__(self):
        return self.name

forms.py

class AddProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        exclude = ['user']

views.py

@login_required
@supplier_required
def Addproduct(request):
    title = "Add New Product"
    form = AddProductForm()
    if request.method == 'POST':
        form = AddProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            messages.success(request, "Product Added Successfully")
            return redirect('product')
        else:
            messages.error(request, "Error Adding Product")

    context = {"form":form, "title":title}

    return render(request, "core/addproduct.html", context)

addproduct.html

<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <div class="form-row">
    <div class="form-group col-md-4 mb-0">
      {{ form.name|as_crispy_field }}
    </div>
    <div class="form-group col-md-4 mb-0">
      {{ form.price|as_crispy_field }}
    </div>
    <div class="form-group col-md-4 mb-0">
      {{ form.quantity|as_crispy_field }}
    </div>
  </div>
  <div class="form-row">
    <div class="form-group col-md-6 mb-0">
      {{ form.country|as_crispy_field }}
    </div>
    <div class="form-group col-md-6 mb-0">
      {{ form.image|as_crispy_field }}
    </div>
  </div>
  {{ form.description|as_crispy_field }}
  <button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">Add Product</button>
</form>
coderboy
  • 741
  • 2
  • 17

0 Answers0