我正在Django中构建一个非常简单的表单,并希望在Bootstrap警报标签中显示表单错误。我知道如何执行此操作(例如Django docs或Django Forms: if not valid, show form with error message或How to render Django form errors not in a UL?
)。但是,当我这样做时,我看到错误出现了两次。似乎模板中Django的{{ form }}
元素除了我自定义格式的错误外,默认情况下还在ul
标签中显示错误。
避免重复的最佳方法是什么?
在template.html
中:
<!--Load the file search form from the view-->
<form action="" method="post" id="homepage_filesearch">
<!--Show any errors from a previous form submission-->
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
{{ csrf_input }}
{{ form }}
<button class="btn btn-primary" type="submit">Search</span></button>
</form>
在views.py
中:
from .forms import FileSearchForm
def view(request):
# Create a form instance and populate it with data from the request
form = FileSearchForm(request.POST or None)
# If this is a POST request, we need to process the form data
if request.method == 'POST':
if form.is_valid():
return form.redirect_to_files()
template = 'template.html'
context = {'form': form}
return render(request, template, context)
在forms.py
中:
class FileSearchForm(forms.Form):
# Define search field
search = forms.CharField(label='', max_length=500, required=True,
empty_value='Search')
def clean_search(self):
# Get the cleaned search data
search = self.cleaned_data['search']
# Make sure the search is either a proposal or fileroot
if some_error_case:
raise forms.ValidationError('Invalid search term {}. Please provide proposal number or file root.'.format(search))
答案 0 :(得分:2)
默认情况下,form
的顶部显示非字段错误。您可以在django source code上看到它:
def _html_output(self, normal_row, error_row,
row_ender, help_text_html, errors_on_separate_row):
"Output HTML. Used by as_table(), as_ul(), as_p()."
# Errors that should be displayed above all fields.
top_errors = self.non_field_errors()
您应该详细说明模板,以避免重复的错误消息,例如Looping over the form’s fields文档的示例:
{{ csrf_input }}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }} #<-- IDK if you want to render field errors.
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
(而不只是{{ form }}
}