form.cleaned_data返回空

时间:2019-05-17 04:14:08

标签: python django

选择一个选项后我有一个问题,我得到了空集。并且表单返回空,并且无法将所选选项保存到数据库中。

这是我的代码:

我有一个表格:

class UserResponseForm(forms.Form):
gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1), widget=forms.CheckboxSelectMultiple, required=False)

我的观点

def responsePenyakit(request):
if request.user.is_authenticated:
    form = UserResponseForm(request.POST or None)
    if form.is_valid():
        gejala1 = form.cleaned_data.get('gejala_id1')
        answer = UserAnswer.objects.all().filter(user_id = request.user.id).order_by('-number_diagnosis')
        user = UserAnswer()
        if(len(answer) > 0):
            user = answer[1]
        else:
            user.number_diagnosis = 0
        if(len(gejala1)>0):
            for i in range(0, len(gejala1)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala1[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis+1
                userAnswer.save()
         return redirect('diagnosis_penyakit:response_matching')
       else:
         raise Http404

还有我的表格:

<form method='POST' action='{% url "diagnosis_penyakit:response"%}' enctype="multipart/form-data"> {% csrf_token %}
{{ form.errors }}
 <div class="row" style="margin-left:10rem;">
    <div class="col-md-3">
        <a onclick="myFunction1()" style="font-size:2rem; color:black;">Tubuh <i class="fas fa-angle-down"></i></a><br/>
        <div id="myDIV1" style="display:none; margin-left:-3rem;">
            {{ form.gejala_id1 }}
        </div>
    </div>
 </div>

还有我的模特:

class UserAnswer(models.Model):
gejala_answer = models.CharField(max_length=250)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
number_diagnosis = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

def __str__(self):
    return self.gejala_answer


class Gejala(models.Model):
penyakit_id = models.IntegerField()
gejala = models.CharField(max_length=150)
id_organ = models.IntegerField(null=False)
status = models.CharField(max_length=150, default='Tetap')
def get_absolute_url(self):
    return reverse('gejala:gejala_detail', kwargs={'pk':self.pk})
def __str__(self):
    return self.gejala

怎么了,我该怎么办? 希望任何人都能帮助我。 我是Django的新手

0 个答案:

没有答案