在 Django 模板中使用 {{ form.as_ul }} 时控制表单错误的显示。
我喜欢方便的输出表单方法 {{ form.as_ul }}
但有没有办法我仍然可以继续使用它,但预先捕获所有错误,而不是在每个字段上方显示错误。
我了解有多种方法可以循环遍历每个表单元素等,如 django docs 但我想继续利用 form.as_ul()
的功能,除了控制错误显示。
I like the convenient output form method {{ form.as_ul }}
but is there a way I can still continue to use it but capture all the errors upfront instead of displaying the error just above each field.
I understand that there are ways to loop through each form element and so on as mentioned in django docs but I want to continue to utilize the capability of form.as_ul()
except get control over error display.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过使用可重用表单模板解决了这个问题。
很简单...
根据您的需要使用以下代码片段创建可重用模板。
如果您想在表单顶部显示所有错误...
如果您想在每个表单字段之后显示所有错误,而不使用错误周围的默认 html 元素... .
使用第二个模板并创建一个 包含标签
Solved this problem by using Reusable Form Templates.
Its simple...
Create a reusable template with the following code snippets based on your need.
If you want to display all errors right at the top of the form...
If you want to display all errors right after each form field without the default html elements around error use...
Used the second template and created a Inclusion Tag
我看到的唯一方法是从
forms.Form
继承新的表单类,并根据需要更改as_ul
方法。如果您要使用第三方表单(例如登录表单等),这不太好(他们不会有此方法)。我认为最好的解决方案是创建自己的 包含标签 并用它渲染表单。它将与
as_ul
({% render_form form %}
) 一样短,但非常灵活,它将适用于所有表单,并且不会混合 HTML 和 Python 代码。The only way I see is to inherit the new form class from
forms.Form
and alteras_ul
method as you like. Which isn't very good if you are going to use third-party forms like login form and so on (they won't have this method).I think the best solution is to create your own inclusion tag and render form with it. It will be as short as
as_ul
({% render_form form %}
) but very flexible, it will work with all forms and won't mix HTML and Python code.我还是觉得模板中渲染表单的定制是相当灵活的。我通常为我的网络应用程序这样做。您可能会使用一点 javascript 和 css,但这不是一个大问题。此外,我认为我们应该尽量让应用程序变得简单。
I still think the customization for rendering form in templates is quite flexible. I usually do this for my webapps. You may work with a bit javascript and css but not a big problem. Moreover, I think we should try to make the app simple.