【发布时间】: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))
【问题讨论】:
标签: python django django-forms django-templates