Horai Nuri
Horai Nuri

Reputation: 5568

Why is my Django form not raising any errors?

I have a simple form and whenever the user does something wrong on the form I'd like to raise a validation error on Django. The problem is that I set up the form validation but when the form is submitted with wrong values, it goes through. I was wondering why it's happening and how I can avoid that?

Here is the html form:

<form id="ask-project" method="post" action="{% url 'ask-project' %}">
  {% csrf_token %}

  <input required="required" class="form-control form-text required" id="prenom" name="prenom" type="text">

  <button class="btn btn-default submit">Submit</button>
</form>

views.py:

def askProject(request):
    if request.method == 'POST':
        form = AskProjectForm(request.POST)
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.save()
            return redirect('/merci/') #success

forms.py:

class AskProjectForm(forms.ModelForm):
    class Meta:
        model = AskProject
        fields = ['prenom']

    def clean_prenom(self):
        prenom = self.cleaned_data['prenom']
        if len(prenom) < 3:
            raise ValidationError('Votre prénom doit etre plus long que 1 caractère.')
        return prenom

Am I doing something wrong?

Upvotes: 2

Views: 549

Answers (1)

e4c5
e4c5

Reputation: 53734

With the pattern that you are using, this sort of problem is inevitable and order of the day. The first thing is not to render the form manually as you appear to be doing. That means you are not showing any feedback when the user enters invalid data. Consider using {{ form }}, {{ form.as_table }} etc or rendering the fields with all information as described here: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually

Second problem is that you are redirecting when the form is submitted, regardless of whether it's valid or not. The recommended pattern is to redirect only when the form is valid. So even if you apply the suggestion in the first para, you are still not getting the required feedback. Consider implementing the form as suggested in the manual. A straight copy past follows

if request.method == 'POST':
    # create a form instance and populate it with data from the request:
    form = NameForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        # ...
        # redirect to a new URL:
        return HttpResponseRedirect('/thanks/')

# if a GET (or any other method) we'll create a blank form
else:
    form = NameForm()

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

Finally getting onto the specific case of why your form validation doesn't work, add a print statement in your clean method to print out both the string and it's length see if it tallies (or if your method even gets called)

Upvotes: 2

Related Questions