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 forms.py 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 views.py 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):
  datas=Product.objects.get(pk=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():
         form.save()
         return HttpResponse('Success')
   else:
      return HttpResponse('Fail')
 template_name='test.html'
 context={'datas':datas}
 return render(request, template_name, context)

Now update your forms.py 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:
            instance.save()

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here