12

I often find myself using a ModelForm in views to display and translate views. I have no trouble displaying the form in the template. My problem is that when I am working with these, the forms often don't validate with the is_valid method. The problem is that I don't know what is causing the validation error.

Here is a basic example in views:

def submitrawtext(request):
    if request.method == "POST":
        form = SubmittedTextFileForm()
        if form.is_valid():
           form.save()
           return render(request, 'upload_comlete.html')
        return render(request, 'failed.html')
    else:
        form = SubmiittedTextFileForm()
        return render(request, 'inputtest.html', {'form': form})

I know that the form is not validating because I am redirected to the failed.html template, but I never know why .is_valid is false. How can I set this up to show me the form validation errors?

2 Answers 2

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})
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.