Skip to content Skip to sidebar Skip to footer

How To Overwrite Save Method In Django Model Form

i'm trying to overwrite save method in my forms.py ,i have to prevent from creating duplicated objects , and if the object exists only update some fields class Item(models.Model):

Solution 1:

This is How I usually overwrite save method in model form:

defsave(self, commit=True):
    # your logic or Save your object for example:
    obj = Model.objects.create(...)
    return obj  

Or you can also do this:

defsave(self, commit=True): 
    obj = super().save(commit=False)
    # do you logic here for example:
    obj.field = something
    
    if commit:
        # Saving your obj
        obj.save()
    return obj

Solution 2:

According to the documentation for ModelForm.save():

A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model.

This means that in your createNewProduct view, when handling POST requests, you need to check whether an Item already exists in the database and if so pass it to the Form constructor for editing, otherwise instantiate the ModelForm as per usual to create a new Item. So actually there's no need to override the ModelForm's save method

Since you want to add the old and new quantities instead of overwriting them you need to take care of that before the form is saved. This should typically happen in the form's clean method.

The resulting ItemForm and createNewProduct view would then look like this:


classItemForm(forms.ModelForm):
      classMeta:
          model = Item
          fields = ['item','quantity']

      defclean(self):
          cleaned_data = super().clean()

          # if this Item already existsif self.instance:
             # add the old quantity to the new quantity
             cleaned_data['quantity'] += self.instance.quantity
          return cleaned_data

defcreateNewProduct(request):

   if request.method == 'POST':
       try:
           dbItem = Item.objects.get(item=request.POST['item'])
       except Item.DoesNotExist:
           # get form for new Item
           form = ItemForm(request.POST)
       else:
           # get form for existing Item
           form = ItemForm(request.POST,instance=dbItem)
       finally:
           if form.is_valid():
              form.save()
              return redirect('success') # redirect on successreturn redirect('failure') #redirect on failure else:
       form = ItemForm()

   return render(request,'temp/add_item.html',{'form':form})  

Post a Comment for "How To Overwrite Save Method In Django Model Form"