Answer a question

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?

Answers

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})
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐