Hide fields from SearchForm depending on the request user groups

27 views Asked by At

I have a StockSearchForm:

class StockSearchForm(CustomForm):
    component__code__icontains = forms.CharField(label=_('component code'),
                                                 required=False)
    component__name__icontains = forms.CharField(label=_('component name'),
                                                 required=False)
    component__product__icontains = forms.ChoiceField(
        label=_('product'), required=False, choices=b_choice + PRODUCT_CHOICES)
    inventory = forms.BooleanField(label=_('to inventory'), required=False)

    def __init__(self, *args, **kwargs):
        super(StockSearchForm, self).__init__(*args, **kwargs)
        self.fields[
            'component__code__icontains'].widget.attrs[
            'class'] = 'form-control'
        self.fields[
            'component__name__icontains'].widget.attrs[
            'class'] = 'form-control'
        self.fields[
            'component__product__icontains'].widget.attrs[
            'class'] = 'form-control'
        self.fields['inventory'].widget.attrs['class'] = 'btn pull-left'
        self.fields['inventory'].initial  = False

The field that is named inventory I only need to display it if the request user has groups "Administrator" or "Purchasing". I tried many codes that I found but neither works, can someone how to do it?

I tried doing

if not request.user.groups.filter(name__in["Admnistrator", "Purchasing"]).exists():
            del self.fields['inventory']

and even

self.fields['inventory'].widget = forms.HiddenInput()

but nothing works for me

(I know that I'm not setting request as a parameter, but I tried setting it obviously even user as a parameter

0

There are 0 answers