自定义格式的 Django 表单错误出现两次
Posted
技术标签:
【中文标题】自定义格式的 Django 表单错误出现两次【英文标题】:Custom-formatted Django form errors appearing twice 【发布时间】:2019-05-11 15:42:10 【问题描述】:我正在 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))
无效搜索后的结果:
【问题讨论】:
【参考方案1】:默认情况下,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 doc 的示例:
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
【讨论】:
以上是关于自定义格式的 Django 表单错误出现两次的主要内容,如果未能解决你的问题,请参考以下文章
53 记一次自定义 classloader 导致的 metadataspace OOM