模板上不显示表单错误?

时间:2013-09-30 18:54:51

标签: django forms validation

当我输入无效的电子邮件地址时,我无法看到错误消息,例如“这不是无效的电子邮件”。

我的comment_form.html:

{% load i18n %}

    <form action="/comment/create/" method="post">
        {% csrf_token %}
            {{ form.errors }}
            {% for field in form %}
            <div class="fieldWrapper">
                {{ field.label_tag }}
                {{ field }}<p>
            </div>

            {% endfor %}
            <input type="hidden" name = "object_id" value="{{object_id}}"  />
            <input type="hidden" name= "next" value="{{ next }}" />
        <input type="submit" value="{% trans "Submit" %}">

    </form>

我的post_detail.html:

extends "base.html" %}



{% block content %}
<div id="exap">


    {{ post.content }}

</div>
<div class="comment">
    {% for comment in comments %}
        <user>{{ comment.owner }}</user>
        {{ comment.content}}
    {% endfor %}


</div>
{% include "comment_form.html" %}


{% endblock %}

这是我的评论。视图

   def create(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        email = request.POST.get('email')
        next = request.POST.get('next')
        if form.is_valid():
            content_type = ContentType.objects.get(app_label="post", model="post")
            object_id = request.POST["object_id"]
            comment = Comment.objects.create(
                content_type = content_type,
                object_id = object_id,
                content = request.POST.get('content'),
                owner= request.POST.get('owner'),
                email = request.POST.get('email')
            )
        else:
            print form.errors
    else:
        form = CommentForm()
    return HttpResponseRedirect(next)

模板中是否显示错误消息?

我哪里错了?

1 个答案:

答案 0 :(得分:1)

karthikr试图告诉你评论中有什么问题。您没有使用该表单进行验证,因此不会显示任何错误。您应该在表单类中使用电子邮件验证代码,而在视图中调用if validateEmail(email),而不是if form.is_valid()

另外,当你编写表单的clean_email方法时,你应该捕获ValidationError:这就是将错误传递给表单错误列表的方式。