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?
To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.
Probably the most common method is to display the error at the top of the form. To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django.
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
Couple of things:
You are not taking the POST
being sent to the POST.
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})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With