我正在 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))
请您参考如下方法:
默认情况下,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 }}
