Today i will tell you how to auto update fields in Django?

Suppose you are working with Django forms and you have multiple fields in your Django model, and you want to update some fields of that model, here i will giude you how you can do this.

First create a file and import your model name there…

from myapp.models import Product
from django import forms

class UpdateForm(forms.ModelForm):
   model = Product
   fields = ['name', 'image', 'status']

I have multiple fields in my Product models but i want to update only 3 fields, if you want to update all fields then you can use fields = ‘__all__’

Now go to your file, and write your code for update the form

from myapp.models import Product
from myapp.forms import UpdateForm
from django.shortcuts import render, redirect

def myview(request, id):
  form = UpdateForm(instance=datas)
  if request.method === 'POST'
      form = UpdateForm(request.POST or None, request.FILES or None, instance=datas)
      if form.is_valid():
         return HttpResponse('Success')
      return HttpResponse('Fail')
 return render(request, template_name, context)

Now update your file with this code…

class UpdateForm(forms.ModelForm):
    def save(self, commit=True):
        instance = super(UpdateForm, self).save(commit=False)

        # Set status if saving picture
        if instance.image:
            instance.status = 1

        if commit:

Let me explain to you what this form does, When you will upload the image using this form it will automatically change the status of your database. If your default status is 0 then after uploading the image it will be 1


Please enter your comment!
Please enter your name here