Skip to content
Advertisement

How to update the one attribute of model once form is validated in Django?

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 ?

Advertisement

Answer

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')
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement