如何在Django中正确显示form.errors消息

时间:2019-05-17 13:22:33

标签: django

在此代码中,表单错误无法正确显示。所有错误消息均显示,仅此字段为必填字段。我如何在模板中定义我的自定义form.error消息。

  

模板

 {% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <p> {{ error }} </p>
        {% endfor %}
    {% endfor %}
{% endif %}
      <div class="form-group">
                        <h5>Full Name <span class="text-danger">*</span></h5>
                        <div class="controls">
                            <input type="text" name="name" class="form-control" title="Full Name is required" > </div>
                    </div>
                    <div class="form-group">
                        <h5>Courses<span class="text-danger">*</span></h5>
                           <div class="controls">
                     {% for course in courses %}
                     <input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.id}}" autofocus  title="Please Check at least one course">
                     <label for="course-{{course.id}}">{{course.title}}</label>
                     {% endfor %}
                   </div>
                    </div>
  

views.py

if request.method == 'POST':
        form = AddStudentForm(request.POST, request.FILES)
        if form.is_valid():
            student = form.save(commit=True)

            student.save()

            messages.success(request, 'student with name  {}  added.'.format(student.name))
            return redirect('admin:add_student')

    else:
        form = AddStudentForm()
    return render(request, 'admin/add_student.html', {'form': form}) 

1 个答案:

答案 0 :(得分:1)

您的views.py中的表单通过这样的错误

if request.method == 'POST':
    form = AddStudentForm(request.POST, request.FILES)
    if form.is_valid():
        student = form.save(commit=True)

        student.save()

        messages.success(request, 'student with name  {}  added.'.format(student.name))
        return redirect('admin:add_student')

    return render(request, 'admin/add_student.html', {'form': form}) 
else:
    form = AddStudentForm()
    return render(request, 'admin/add_student.html', {'form': form})

这意味着您应该删除else部分 并在您的模板代码中

{% if form.errors %}
    <div class="alert alert-danger">
        {{ form.errors }}
    </div>
{% endif %}

更新了答案,以便在您首次加载视图时获得正确的答案