Home > Software design >  How to update the one attribute of model once form is validated in Django?
How to update the one attribute of model once form is validated in Django?

Time:11-09

I have a model

class Tutor(models.Model):
    name = models.CharField(max_length=100)
    qualification = models.CharField(max_length=100)
    experience = models.CharField(max_length=200)
    tution_fee = models.CharField(max_length=100)
    about = models.CharField(max_length=1000)
    demo_classes_link = models.CharField(max_length=1000)
    contact_number = models.CharField(max_length=10)
    email_id = models.EmailField(null=True, blank=True)
    material = models.CharField(max_length=1000)
    status = models.BooleanField(null=True, blank=True)

and a form

class GeeksForm(forms.ModelForm):
    # specify the name of model to use
    class Meta:
        model = Tutor
        fields = "__all__"

Now I have captured all the data using POST API form is validated.

def registration(request) :
    form = GeeksForm(request.POST)
    # Check if the form is valid:
    if form.is_valid():
        number = request.POST['contact_number']
        print(number)
        r = requests.get('http://apilayer.net/api/validate?access_key=***********&number=*******&country_code= 91&format=1', params=request.GET)
        if r.status_code == 200:
            form['status'] = 1 # I want to update this once is form is validated, django throws an error.
            form.save()
            return HttpResponse('Yay, it worked')
        currentID = form.auto_id
        print(currentID)
       # form = GeeksForm()
    else :
        print("Invalid")   
    return render(request, 'Tutorform.html', {'form': form})  

How do I update status parameter of model in django after form validation is successful ?

CodePudding user response:

Change form['status'] = 1 to form.cleaned_data['status'] = True

When a form is validated, its data is also "cleaned" (i.e. consolidated into one uniform format), and stored in a dictionary called cleaned_data, which is used when saving the form. You should edit it there.

Though, I'm not entirely sure, a BooleanField will probably expect True instead of 1.

It's also possible to save the instance first, and edit status later:

instance = form.save()
instance.status = True
instance.save()

CodePudding user response:

Retrieve the underlying model instance, change the field value and save the form.

if r.status_code == 200:
    myform = form.save(commit=False) #returns model instance object
    myform.status = True
    myform.save()
    return HttpResponse('Yay, it worked')
  • Related