HassanDh
HassanDh

Reputation: 27

Creating new Objects instead of updating - Django

I am trying to use Update in Django, but it is not being updated, rather a new object of the model is being created in the database. For example, if I try to change product label "Laptop" to "Smartphone", Django creates a new product called "Smartphone" instead of updating "Laptop".

This is my code Model:

class Products(models.Model):
     label = models.CharField(max_length=50)
     description = models.CharField(max_length=250)
     first_price = models.FloatField(null=True)
     price = models.FloatField()
     quantity = models.IntegerField(default=0)
     image = models.ImageField(null=True, blank=True)

     def __str__(self):
         return self.label

     @property
     def imageURL(self):
         try:
             url = self.image.url
         except:
             url = ''
         return url

Form:

class ProductForm(ModelForm):
     class Meta:
         model = Products
         fields = ['label', 'description', 'first_price', 'price', 'quantity', 'image']

View:

@login_required(login_url='login')
def editProduct(request, id):
    product = Products.objects.get(id=id)
    form = ProductForm(instance=product)
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, 'Product was edited.')
            return redirect('index')

    context = {
        'form': form
    }
    return render(request, 'store/edit-product.html', context)    

Template:

<h3>Edit Product</h3>

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}

    {{ form.label.label }}
    {{ form.label }}

    {{ form.description.label }}
    {{ form.description }}

    {{ form.first_price.label }}
    {{ form.first_price }}

    {{ form.price.label }}
    {{ form.price }}

    {{ form.quantity.label }}
    {{ form.quantity }}

    {{ form.image.label }}
    {{ form.image }}


    <input type="submit" name="Add product">
    {{form.errors}}
</form>

Thank you in advance.

Upvotes: 1

Views: 956

Answers (1)

Brian Destura
Brian Destura

Reputation: 12068

To update an object, it needs to be passed to the form, so:

    product = Products.objects.get(id=id)
    form = ProductForm(instance=product)
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES, instance=product)
                                                        # ^^^ Add this

Otherwise without instance, the form will work as if you are trying to create a new object

Upvotes: 2

Related Questions