Django - Overriding get_form to customize admin forms based on request

后端 未结 8 957
眼角桃花
眼角桃花 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:13

    In my case, with Django 2.1 you could do the following

    In forms.py

    class ObjectAddForm(forms.ModelForm):
    
        class Meta:
            model = Object
            exclude = []
    
    class ObjectChangeForm(forms.ModelForm):
        class Meta:
            model = Object
            exclude = []
    

    And then in the admin.py

    from your.app import ObjectAddForm, ObjectChangeForm
    
    class ObjectAdmin(admin.ModelAdmin):
        ....
        def get_form(self, request, obj=None, **kwargs):
            if obj is None: 
                kwargs['form'] = ObjectAddForm
            else:
                kwargs['form'] = ObjectChangeForm
            return super().get_form(request, obj, **kwargs)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题