1

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

视图.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 %}
4

1 回答 1

0

好的,解决方案是这样的:

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

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

于 2013-02-13T20:24:27.117 回答