Search code examples
javascripthtmldjangovalidationdjango-forms

Django form validation don't function


I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution. This is my code: (The variables of class are indented)

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

Also I have try this way:

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)

In this case the view corresponding to this form is the following one:

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)

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and 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>

I suppose that the problem can be relation with the reload page, is possible I have to compare the csrf_token or something like this? Can you help me, thanks.


Solution

  • Finally I have solve this putting an HttpResponseRedirect in my views:

    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)