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

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

问题描述

我想在使用 Crispy Forms 时做一些简单的事情;我只想在用户属于员工组时显示字段集.这在像这样的标准模板中很容易解决:

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:

<代码>{% if user.is_staff %}显示额外的东西{% 万一 %}

也许我错过了手册中的某些内容,但我不知道如何将{% if user.is_staff %}"之类的模板标签注入到脆皮表单布局中.如果我可以像下面这样使用虚构的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_staff.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__ 方法中:

Then in your form's __init__ method:

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.

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

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