Django表单验证不起作用

kokeuurv  于 2023-05-08  发布在  Go
关注(0)|答案(3)|浏览(192)

我尝试在我的表单中进行验证,但在我遵循官方文档和教程之后,我没有获得解决方案。这是我的代码:(类的变量是缩进的)

class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer

我也尝试过这种方式:

def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)

在这种情况下,与此表单对应的视图如下所示:

def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)

其中传递给对象的变量用于保存在BBDD中。
实际-------------------------
在尝试了人们在评论中推荐的选项后,我没有看到验证消息,而当我删除了在做表单后重新加载页面的代码部分时,我可以看到验证消息。
HTML和JavaScript:

<div class="col-md-6">
        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}
    </div>

<script>
    
    $(function() {
        var counter = 94;
        $( "#enviar" ).click(function() {
            counter = counter + 1;
                //alert(counter);
                localStorage.setItem("counter",counter);
                alert('Su pregunta ha sido enviada correctamente. ' +
                    'Envía otra y tendras más posibilidades de ganar los Airpods.');
            });
        $('#askFortm').on('submit', function(e) {
              e.preventDefault();
              setTimeout(function() {
                   window.location.reload();
              },0);
              this.submit();
        });
    });
    
    </script>

我想这个问题可能与重新加载页面有关,可能我必须比较csrf_token或类似的东西?你能帮我吗,谢谢。

0qx6xfy6

0qx6xfy61#

class QuestionForm(forms.Form):
    subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
    question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
    answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
    answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

    def clean_question(self):
        question = self.cleaned_data.get('question')
        a = "0"
        if a not in question:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return question

    def clean_answer(self):
        answer = self.cleaned_data.get('answer')
        a = "0"
        if a not in answer:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return answer
6jygbczu

6jygbczu2#

我相信当用户没有在必须字段中给予值时,问题或答案将为空,因此下面的代码应该可以工作。

class QuestionForm(forms.Form):
    subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
    question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
    answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
    answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

    def clean_question(self):
        question = self.cleaned_data.get('question')

        if not question:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return question

    def clean_answer(self):
        answer = self.cleaned_data.get('answer')

        if not answer:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return answer
6psbrbz9

6psbrbz93#

最后,我在我的视图中放置了一个HttpResponseRedirect来解决这个问题:

def ayudanos(request):
form = QuestionForm(request.POST or None)
if form.is_valid():
    form_data = form.cleaned_data
    subject = form_data.get("subject")
    question = form_data.get("question")
    answer = form_data.get("answer")
    answerOne = form_data.get("answerOne")
    answerTwo = form_data.get("answerTwo")
    name = form_data.get("name")
    email = form_data.get("email")
    obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                      answerTwo=answerTwo, name=name, email=email)
    return HttpResponseRedirect(reverse('ayudanos'))
context = {
    "form": form
}
return render(request, "ayudanos.html", context)

相关问题