Django - Overriding get_form to customize admin forms based on request -
i've tried various methods achieve this.
i decided against overriding formfield_for_dbfield it's doesn't copy of request object , hoping avoid thread_locals hack.
i settled on overriding get_form in modeladmin class , tried following:
class pageoptions(admin.modeladmin): def get_form(self, request, obj=none, **kwargs): if request.user.is_superuser: self.fieldsets = ((none, {'fields': ('title','name',),}),) else: self.fieldsets = ((none, {'fields': ('title',),}),) return super(pageoptions,self).get_form(request, obj=none, **kwargs)
when print fieldsets or declared_fieldsets within get_form none (or whatever set initial value in pageoptions).
why doesn't work , there better way this?
i have no idea why printing property doesn't give want assigned (i guess may depends on print, exactly), try overriding get_fieldsets
instead. base implementation looks this:
def get_fieldsets(self, request, obj=none): if self.declared_fieldsets: return self.declared_fieldsets form = self.get_formset(request).form return [(none, {'fields': form.base_fields.keys()})]
i.e. should able return tuples.
edit andybak. 4 years on , found own question again when trying similar on project. time went approach although modified avoid having repeat fieldsets definition:
def get_fieldsets(self, request, obj=none): # add 'item_type' on add forms , remove on changeforms. fieldsets = super(itemadmin, self).get_fieldsets(request, obj) if not obj: # add form if 'item_type' not in fieldsets[0][1]['fields']: fieldsets[0][1]['fields'] += ('item_type',) else: # change form fieldsets[0][1]['fields'] = tuple(x x in fieldsets[0][1]['fields'] if x!='item_type') return fieldsets
Comments
Post a Comment