【问题标题】:Django form validation don't functionDjango 表单验证不起作用
【发布时间】:2017-11-14 23:22:50
【问题描述】:

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

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 或类似这样的想法? 你能帮我吗,谢谢。

【问题讨论】:

  • 现在,它用这个表单的视图实现了我的评论。

标签: javascript html django validation django-forms


【解决方案1】:
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

【讨论】:

  • 您的代码工作正常,但问题不在这里,注释已实现。
【解决方案2】:

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

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

【讨论】:

  • 该字段默认使用什么样的数据?
  • 对不起,这段代码很好用,我的代码和第一条评论的代码如何工作,我正在编辑评论以再次解释问题,因为问题是由 javascript 代码部分引起的。跨度>
  • 只是一部分,现在评论已经实现了。
【解决方案3】:

最后我解决了这个问题,在我的视图中添加了一个 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-27
    • 2018-01-23
    • 2012-02-02
    • 1970-01-01
    • 2021-12-01
    • 2019-01-26
    • 2020-09-13
    相关资源
    最近更新 更多