如何检测模板中的表单集是否有任何错误?

发布于 2024-09-11 11:02:04 字数 1089 浏览 2 评论 0原文

感谢 django 中出色的内联模型表单集,我拥有了一个非常高级的表单,其中包含 4 个内联表单集。在模板中,我在选项卡中显示每个表单集。一切工作都非常顺利,但如果该选项卡中的表单集有任何验证错误,我想将选项卡着色为红色。所以我尝试了这个:

<div id="tabs">
    <ul>
        <li><a href="#foo-tab"{% if forms.FooFormSet.errors %} class="error"{% endif %}>Foo</a></li>
        <li><a href="#bar-tab"{% if forms.BarFormSet.errors %} class="error"{% endif %}>Bar</a></li>
        <li><a href="#zoo-tab"{% if forms.ZooFormSet.errors %} class="error"{% endif %}>Zoo</a></li>
        <li><a href="#doo-tab"{% if forms.DooFormSet.errors %} class="error"{% endif %}>Doo</a></li>
    </ul>

    <div id="foo-tab"></div>
    <div id="bar-tab"></div>
    <div id="zoo-tab"></div>
    <div id="doo-tab"></div>
</div>

但它不起作用,因为 forms.*Set.errors 是一个包含空字典的列表(因此它总是返回 True),如 [{}, {}, {}] (表单集中的表单数量为formset.errors 中的空字典数量相同

我认为一个解决方案可能是子类化 BaseInlineFormSet 并添加 has_errors 方法或其他方法,然后为我的所有表单集使用该子类化基类还有其他建议吗?

Thanks to the fantastic inline model formsets in django I have a pretty advanced form with 4 inline formsets. In the template I display each formset in a tab. Everything works really slick but I would like to color a tab red if the formset in that tab has any validation errors at all. So I tried this:

<div id="tabs">
    <ul>
        <li><a href="#foo-tab"{% if forms.FooFormSet.errors %} class="error"{% endif %}>Foo</a></li>
        <li><a href="#bar-tab"{% if forms.BarFormSet.errors %} class="error"{% endif %}>Bar</a></li>
        <li><a href="#zoo-tab"{% if forms.ZooFormSet.errors %} class="error"{% endif %}>Zoo</a></li>
        <li><a href="#doo-tab"{% if forms.DooFormSet.errors %} class="error"{% endif %}>Doo</a></li>
    </ul>

    <div id="foo-tab"></div>
    <div id="bar-tab"></div>
    <div id="zoo-tab"></div>
    <div id="doo-tab"></div>
</div>

But it doesnt work because forms.*Set.errors is a list with empty dictionarys (so it will always return True) like [{}, {}, {}] (the amount of forms in the formsets is the same amount of empty dictionarys in formset.errors

One solution I think could be to subclass BaseInlineFormSet and add a has_errors method or something, and then use that subclassed base for all my formsets. Any other suggestions? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心舞飞扬 2024-09-18 11:02:04

您可以检查表单集方法 is_valid 的结果,该方法又检查每个表单的有效性:{% if forms.FooFormSet.is_valid %}

据我所知,如果表单已经经过验证,则或多或少是无操作(不触及数据库,不重新验证表单),因此根本不会损害性能。

You can check the result of the formset's method is_valid, which in turn checks each form for validity: {% if forms.FooFormSet.is_valid %}.

As far as I know, it is more or less a no-op (database is not touched, forms are not revalidated) if the forms have already undergone validation, so it is not going to hurt the performance at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文