Django form not validating and saving into db

Submitted 3 years, 2 months ago
Ticket #367
Views 440
Language/Framework Django
Priority Medium
Status Closed

I'm not sure how to save the form into the database. I know the form is not valid because I tried do something else within that conditional. This is my models. I have the same thing for multiple values in models.

from django.db import models
class Test(models.Model):
    happy = models.CharField(
        max_length = 2,
    )
...
    interest = models.CharField(
        max_length = 2,
    )

Below is my form

from django import forms
from .models import Test
class TestForm(forms.ModelForm):
    happy = forms.MultipleChoiceField(
        required=True,
        label='You feel happy / content',
        widget=forms.RadioSelect,
        choices = emotion_choices,
    )
...
    interest = forms.MultipleChoiceField(
        required=True,
        label='What creative outlet do you prefer?',
        choices=system_choices,
    )
    
    def clean_init_form(self):
        new_init_form = Initial.objects.create(
            happyAns = self.cleaned_data['happy'],
            sadAns = self.cleaned_data['sad'],
            tiredAns = self.cleaned_data['tired'],
            jitAns = self.cleaned_data['jittery'],
            scaleAns = self.cleaned_data['scale'],
            interAns = self.cleaned_data['interest'],
        )
        return new_init_form

    class Meta:
        model = Initial
        fields = "__all__"

Below is my view,

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import initialForm
from .models import Test

def submitForm(request):
    if request.method == 'POST':
        form = TestForm(request.POST)

        # create a form instance and populate it with data from the request:
        
        # check whether it's valid:
        if form.is_valid():
            happy = form.cleaned_data['happy']
            sad = form.cleaned_data['sad']
            tired = form.cleaned_data['tired']
            jittery = form.cleaned_data['jittery']
            scale = form.cleaned_data['scale']
            interest = form.cleaned_data['interest']

            form.save()
            return HttpResponseRedirect('/exit')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = TestForm()

    return render(request, 'survey.html', {'form': form})

Submitted on Mar 04, 21

can you check print(form.errors) and see whats you are getting? - Vengat 3 years, 2 months ago

kapjakal, have you checked for the errors. can you provide more information so that our SME's can provide the solution - revathirv 3 years, 2 months ago
add a comment

1 Answer

Verified

Its resolved after added the form.is_valid method. Thanks.

Submitted 3 years, 2 months ago


Latest Blogs