在字段旁边显示django form.errors

时间:2019-06-18 07:37:32

标签: django django-forms

提交django实现的表单后出现错误时,它将显示在我有form.errors的页面顶部。在这里,我希望将该错误显示在由于错误而导致出现错误的字段旁边,就像在django用户创建表单中一样。此外,输入的值在错误消息之后都消失了。怎么做??

  

forms.py

class AddVendorForm(forms.ModelForm):
    class Meta:
        model = Vendor
        fields = '__all__'
  

views.py

def add_vendor(request):
    if request.method == 'POST':
        form = AddVendorForm(request.POST or None)
        if form.is_valid():
            vendor = form.save(commit=False)
            vendor.save()
            messages.success(request, '{} vendor added.'.format(vendor.name))
            return redirect('add_vendor')
    else:
        form = AddVendorForm()
    return render(request, 'add_vendor.html', {'form': form})
  

模板

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

<form action="{% url 'add_vendor' %}" method="post">
   {% csrf_token %}

    <h5>Name <span class="text-danger"></h5>

      <input type="text" name="name" class="form-control" required>

       <h5>Address <span class="text-danger"></h5>

     <input type="text" name="address" class="form-control" >

 <h5>Contact Number <span class="text-danger"></h5>

    <input type="text" name="contact" class="form-control" required>

   <button type="submit" class="btn btn-info">Add</button>
                        </form>

2 个答案:

答案 0 :(得分:1)

遍历表单字段

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
        <div class="alert alert-danger">{{ field.errors }}</div> 
    </div>
{% endfor %}

参考:https://docs.djangoproject.com/en/2.2/topics/forms/#looping-over-the-form-s-fields

答案 1 :(得分:1)

{{form.errors}}的错误。您可以这样尝试

<div class="alert alert-danger">
        <ul>
            {% for field in form %}
                {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
            {% endfor %}
        </ul>
</div>