Conditionally display a Fieldset with Crispy Forms

前端 未结 2 1989
死守一世寂寞
死守一世寂寞 2021-01-27 11:57

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 th

2条回答
  •  囚心锁ツ
    2021-01-27 12:47

    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))
    

    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.

提交回复
热议问题