Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading