使用bootstrap以django模型形式显示自定义错误消息

时间:2016-05-07 12:43:41

标签: django twitter-bootstrap

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

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

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

1 个答案:

答案 0 :(得分:2)

form.name.error_messages更改为模板中的form.name.errors

您似乎手动逐个呈现字段/错误,解释here

您可能需要考虑使用{% for %}模板标记的更自动的方法。

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

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