使用Bootstrap以Django模型形式显示自定义错误消息 [英] Showing custom error messages in django model form with bootstrap

查看:49
本文介绍了使用Bootstrap以Django模型形式显示自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果某些字段无效,我想显示自定义错误消息.我有以下模型:

I want to show custom error messages, if some field is not valid. I have following model:

class Test(models.Model):
    name = models.IntegerField(max_length=10)


class TestForm(forms.ModelForm):

    class Meta:
        model = Test
        fields = '__all__'
        error_messages = {
            'name': {
                'max_length': ("This user's name is too long."),
            },
        }

视图是:

def test(request):
    if request.method == 'POST':
        print "The form is submitted successfully."
        form = TestForm(request.POST)
        if form.is_valid():
            print request.POST.get("name")
            return render(request, 'test.html',{'form' : TestForm()})
        else:
            print "Something wrong with inputs."
            return render(request, 'test.html',{'form' : form})
    else:
        return render(request,'test.html',{'form' : TestForm()})

和模板是:

{% extends "base.html" %}
{% block title %}
Test Form
{% endblock title %}  

{% load widget_tweaks %}

{% block body_block %}
<h1>hello from test</h1>    

<form class='form-horizontal' role='form' action="." method="POST">
    <div class='form-group'>

        <label class='control-label col-md-2 col-md-offset-2' for='id_name'>Name</label>
        <div class='col-md-6'>

            {% render_field form.name class="form-control" placeholder="Full Name" type="text" %}
            {{ form.name.error_messages }} 
            {# I want to add here classes for alert-error etc #}
        </div>
    </div>
    {% csrf_token %}

    <div class='form-group'>
        <div class='col-md-offset-4 col-md-6'>
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </div>


</form>    
{% endblock body_block %}

但是,我在模板中没有收到任何消息.请帮我解决这个问题.

But, I am not getting any messages in the template. Please help me to solve this.

推荐答案

在模板中将 form.name.error_messages 更改为 form.name.errors .

您可能想考虑使用 {%for%} 模板标签.

You may want to consider a more automatic approach using a {% for %} template tag.

编辑:要更改默认错误消息,您需要以 Meta 形式更新您的 error_messages 并覆盖django使用的密钥,在这种情况下,它是基于invalid ="nofollow"> IntegerField 来源:

To change the default error message, you need to update your error_messages in the form Meta and overwrite the key used by django, in this case it is key invalid, based on IntegerField source:

class Meta:
    model = Test
    fields = '__all__'
    error_messages = {
        'some_integer_field': {
            'invalid': 'some custom invalid message',
        },
    }

这篇关于使用Bootstrap以Django模型形式显示自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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