[Solved]-Displaying django form validation errors for ModelForms

21👍

Couple of things:

  1. You are not taking the POST being sent to the POST.

  2. To see the error message, you need to render back to the same template.

Try this:

def submitrawtext(request):
    if request.method == "POST":
        form = SubmittedTextFileForm(request.POST)
        if form.is_valid():
           form.save()
           return render(request, 'upload_comlete.html')
        else:
           print form.errors #To see the form errors in the console. 
    else:
        form = SubmittedTextFileForm()
    # If form is not valid, this would re-render inputtest.html with the errors in the form.
    return render(request, 'inputtest.html', {'form': form})

3👍

I faced the same annoying problem and solved it by returning the form.errors.values() back with HttpResponse. Here is the code:

@csrf_exempt
def post(request):

    form = UserForm(request.POST)

    if form.is_valid():
        return HttpResponse('All Good!')
    else:
        return HttpResponse(form.errors.values())  # Validation failed

In my case it returned:

<ul class="errorlist"><li>This field is required.</li></ul>
<ul class="errorlist"><li>This field is required.</li></ul>
<ul class="errorlist"><li>This field is required.</li></ul>
<ul class="errorlist"><li>This field is required.</li></ul>

It doesn’t provide much information, but it is enough to give you an idea.

Leave a comment