显示ModelForms的Django表单验证错误 [英] displaying django form validation errors for ModelForms

查看:72
本文介绍了显示ModelForms的Django表单验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己在视图中使用ModelForm来显示和转换视图.我毫不费力地在模板中显示表单.我的问题是,当我使用它们时,表单通常不使用is_valid方法进行验证.问题是我不知道是什么导致验证错误.

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

我知道该表单无法验证,因为我被重定向到了fail.html模板,但是我永远不知道为什么.is_valid为false.我该如何设置以向我显示表单验证错误?

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?

推荐答案

事物的结合:

  1. 您没有将POST发送到POST.

要查看错误消息,您需要渲染回相同的模板.

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

尝试一下:

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

这篇关于显示ModelForms的Django表单验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆