Django - formset.errors垂直显示而不是水平显示

时间:2013-02-13 20:14:50

标签: django django-views

当引发formset.errors时,错误消息的每个字母都显示在一个新行上,而不是水平显示在一行上。

views.py

def createNewMap(request):
    if request.user.is_authenticated():
        formset = ezAppFormSet()
        if request.method == 'POST':
            formset = ezAppFormSet(request.POST)
            if formset.is_valid():
                instance = formset.save(commit=False)
                instance.created_by = request.user
                try:
                    instance.save()
                except IntegrityError:
                    formset.errors["name"] = u"This name already exists"

        return render_to_response("ezmapping/manage_new_App.html", {'formset': formset, 'title': "New EzApp"}, context_instance=RequestContext(request))
    else:
        error_msg = u"You are not logged in"
        return HttpResponseServerError(error_msg)

模板:

{% extends "basemap.html" %}
{% block content %}
<table border="1">
<tr>
<td>
    <h1>Define App options</h1>
    {% if formset.errors %}
        <p style="color: red;">
            Please correct the error{{ formset.errors|pluralize }} below.
        </p>
    {% endif %}
    <form method="post" action="" encrypt="multipart/form-data">{% csrf_token %}
            {{ formset.as_p }} 
        <input type="submit" value="Submit" onclick="initialize()">
    </form>
</td>
</tr>
</table>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

好的解决方案是:

formset.errors["name"] = [u"This name already exists"]

form.errors获得一个词典:https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.errors