Showing custom error messages in django model form with bootstrap

我们两清 提交于 2021-01-29 07:46:30

问题


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."),
            },
        }

The view is:

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

and template is:

{% 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.


回答1:


Change form.name.error_messages to form.name.errors in your template.

It seems you render fields/errors one by one manually, explained here:

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

EDIT: 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',
        },
    }


来源:https://stackoverflow.com/questions/37088697/showing-custom-error-messages-in-django-model-form-with-bootstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!