Removing fields from a dynamic ModelForm

In ModelForm, I need to check user permissions so that they fill in the correct fields:

It is defined as follows:

class TitleForm(ModelForm):    
    def __init__(self, user, *args, **kwargs):
        super(TitleForm,self).__init__(*args, **kwargs)            
        choices = ['','----------------']
        # company
        if user.has_perm("myapp.perm_company"): 
            self.fields['company'] = forms.ModelChoiceField(widget=forms.HiddenInput(),
                queryset=Company.objects.all(), required=False) 
            choices.append(1,'Company')
        # association
        if user.has_perm("myapp.perm_association")
            self.fields['association'] =
            forms.ModelChoiceField(widget=forms.HiddenInput(),
                queryset=Association.objects.all(), required=False)
            choices.append(2,'Association')
        # choices
        self.fields['type_resource'] = forms.ChoiceField(choices = choices)

    class Meta:
        Model = Title  

This ModelForm does the job: I hide every field in the template and make them appear thanks to javascript ...
The problem is that ModelForm is that every field defined in the model will be displayed on the template.
I would like to remove them from the form if they are not needed:
Example: if the user does not have the right to a company model, he will not be used in the rendered form in the template.

, Meta fields exclude, , .

?
.

+5
1

self.fields dict:

if not user.has_perm("blablabla"):
    del self.fields["company"]
+9

All Articles