简体   繁体   中英

django forms exclude fields on init rather than in the meta class

I want to exclude certain fields in the init function of a modelform depending on a parameter passed in, how do I do this? I know I can add exclude fields using the meta class of a model form but I need this to be dynamic depending on the variable passed in.

Thanks

您可以在调用super之后修改self.fields列表。

You should use modelform_factory to create the form on the fly and pass in the fields you want to exclude.

def django.forms.models.modelform_factory   (       
     model,
    form = ModelForm,
    fields = None,
    exclude = None,
    formfield_callback = lambda f: f.formfield()     
)   

So something like

modelform_factory(MyModel, MyModelForm, exclude=('name',))

你应该使用self._meta而不是self.Meta ,因为ModelForm.__new__方法获取属性形成self.Meta并将它们放入self._meta

Related, to exclude fields from a sub-class, I have extended the ModelForm class like so:

 class ModelForm(djangoforms.ModelForm):
   def __init__(self, *args, **kwargs):
     super(ModelForm, self).__init__(*args, **kwargs)

     meta = getattr(self, 'Meta', None)
     exclude = getattr(meta, 'exclude', [])

     for field_name in exclude:
       if field_name in self.fields:
         del self.fields[field_name]

Just to note: if your form is called from a ModelAdmin class, just create a get_form method for the ModelAdmin:

def get_form(self, request, obj=None, **kwargs):
    exclude = ()

    if not request.user.is_superuser:
        exclude += ('field1',)

    if obj:
        exclude += ('field2',)

    self.exclude = exclude
    return super(ProfessorAdmin, self).get_form(request, obj, **kwargs)

PS: change ProfessorAdmin by the method "owner" class.

I made like this:

class Meta:
    exclude = [field.label for field in Fields.objects.filter(visible=False)] + ['language', 'created_at']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM