Django - Overriding get_form to customize admin forms based on request

后端 未结 8 967
眼角桃花
眼角桃花 2020-12-04 18:15

I\'ve tried various methods to achieve this.

I decided against overriding formfield_for_dbfield as it\'s doesn\'t get a copy of the request object and I was hoping t

8条回答
  •  天命终不由人
    2020-12-04 19:15

    I have no idea why printing the property doesn't give you want you just assigned (I guess may be that depends on where you print, exactly), but try overriding get_fieldsets instead. The base implementation looks like 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. you should be able to just return your tuples.

    EDIT by andybak. 4 years on and I found my own question again when trying to do something similar on another project. This time I went with this approach although modified slightly to avoid having to repeat fieldsets definition:

    def get_fieldsets(self, request, obj=None):
        # Add 'item_type' on add forms and remove it on changeforms.
        fieldsets = super(ItemAdmin, self).get_fieldsets(request, obj)
        if not obj: # this is an add form
            if 'item_type' not in fieldsets[0][1]['fields']:
                fieldsets[0][1]['fields'] += ('item_type',)
        else: # this is a change form
            fieldsets[0][1]['fields'] = tuple(x for x in fieldsets[0][1]['fields'] if x!='item_type')
        return fieldsets
    

提交回复
热议问题