Django form not validating and saving into db

Submitted 6 months, 2 weeks ago
Ticket #367
Views 99
Language 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? - arun 6 months, 2 weeks ago

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

1 Answer

Verified

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

Submitted 6 months, 1 week ago


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message