Removing a fields from a dynamic ModelForm
Asked Answered
M

1

11

In a ModelForm, i have to test user permissions to let them filling the right fields :

It is defined like this:

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 work : i hide each field on the template and make them appearing thanks to javascript...
The problem is this ModelForm is that each 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:
exemple : if the user has no right on the model Company, it won't be used it in the rendered form in the template.

The problem of that is you have to put the list of fields in the Meta class of the form with fields or exclude attribute, but i don't know how to manage them dynamically.

Any Idea??
Thanks by advance for any answer.

Mitman answered 25/3, 2010 at 10:48 Comment(0)
H
17

Just delete it from the self.fields dict:

if not user.has_perm("blablabla"):
    del self.fields["company"]
Holsworth answered 25/3, 2010 at 15:35 Comment(4)
Yes, it was obvious!!!! Just have to define all the fields in the Meta class and then removing if not usefull... Thanks a lot!Sine
this won't work if you have fieldset specified on for example in a ModelAdmin.Coati
@NathanKeller quick and dirty: self.fields['field_to_hide'] = forms.CharField(required=False, widget=forms.HiddenInput())Mazy
modifying forms after init has been called has always felt a bit hackish to me. you have to be very cautious what you do! (still in 2018!)Mazy

© 2022 - 2024 — McMap. All rights reserved.