繁体   English   中英

Django 表单未验证并保存到数据库中

[英]Django form not validating and saving into db

我不确定如何将表单保存到数据库中。 我知道该表格无效,因为我尝试在该条件下做其他事情。 这是我的模型。 对于模型中的多个值,我有同样的事情。

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

这是我的 forms。 同样,我认为表单不同部分的类似代码不是问题所在。

from django import forms
from .models import Initial
class initialForm(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__"

这是我的看法:

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

from .forms import initialForm
from .models import Initial

def submitForm(request):
    if request.method == 'POST':
        form = initialForm(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 = initialForm()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM