有条件地显示带有脆皮表单的字段集 [英] Conditionally display a Fieldset with Crispy Forms

查看:87
本文介绍了有条件地显示带有脆皮表单的字段集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用Crispy Forms时做一些简单的事情;我只想在用户属于人员组时才显示Fieldset。可以在这样的标准模板中轻松解决此问题:

I want to do something simple while using Crispy Forms; I want show a Fieldset only if the user belongs to the staff group. This is easily solved in a standard templates like this:


{%user.is_staff%}
显示额外的内容东西
{%endif%}

也许我错过了手册中的内容,但是我看不到我如何才能将像 {%if user.is_staff%}这样的模板标签注入到松脆的Layout中。如果我可以使用以下虚构的 Djangotag来解决问题,则对于我的用例来说将是理想的选择:

Maybe I missed something in the manual, but I don't see how I can just inject a template tag like "{% if user.is_staff %}" into the crispy form Layout. It would be ideal for my use case if I could something like the following where I use a fictitious 'Djangotag' to solve my problem:

self.helper.layout = Layout(
   Fieldset(
       'Section One',
       'name',
       'description',
   ),
   Djangotag('{% if user.is_staff %}'),
   Fieldset(
       'Conditional Fieldset',
       'field1',
       'field2',
   ),
   Djangotag('{% endif %}'),      
   Fieldset(
       'More Details',
       'detail1',
       'detail2',
   ),
  )

是否有一种简便的方法来处理脆脆的表格?

Is there an easy way to do this with crispy forms?

注意:我已经实现了 self.user = kwargs.pop('user') 方法,它不是很好,我还在寻找更好的东西。

Note: I already implemented the self.user = kwargs.pop('user') approach and it's not very elegant, I am still looking for something better.

我还尝试为if语句创建简单的模板,并尝试 HTML( {%include'helpers / is_s taff.html’%}),但渲染过程失败。

I also tried created simple templates for the if statements, and tried this, HTML("{% include 'helpers/is_staff.html' %}"), but the render process fails.

推荐答案

您可以将请求上下文从视图传递到表单,然后在表单帮助器中使用它。像这样的东西:

You can pass the request context to your form from the view, and then use this in your form helper. Something like this:

在创建表单的视图函数中:

In the view function that creates the form:

form = MyForm(request.POST, user=getattr(request, 'user', None))

然后以表单的 __ init __ 方法:

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user', None)
    super(MyForm, self).__init__(args, kwargs)

最后在您的表单布局代码中:

And finally in your form layout code:

if user and user.is_staff:
    self.helper.layout.append(Fieldset(
        'Conditional Fieldset',
        'field1',
        'field2',
    ),

我刚刚将此字段集附加到了布局的末尾。 文档给出了您还可以选择其他方式来动态更新布局。

I've just appended this fieldset to the end of the layout. The documentation gives you other options for updating layouts on the fly.

这篇关于有条件地显示带有脆皮表单的字段集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆