A
A
Alexey Belov2018-06-14 22:46:13
Django
Alexey Belov, 2018-06-14 22:46:13

Django how to initialize form fields depending on the user's group?

I have a FormView, also a form for it, how to display to the user only those fields that are available, for example, in the group of managers.

def __init__(self, *args, **kwargs):
        super(CreateCommandForm, self).__init__(*args, **kwargs)

        # if you want to do it to all of them
        for field in self.fields.values():
            field.error_messages = {'required':'Это поле обязательно для заполнения'}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-06-15
@Alenorze

You need to dig in this direction:

class UpdateView(FormView):
     def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

class UpdateForm(forms.Form):
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super().__init__(*args, **kwargs)
        if not user.groups.filter(name='managers').exists():
            self.fields['secret'].disabled = True

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question