Prithviraj Mitra
Prithviraj Mitra

Reputation: 11822

Different form fields for add and change view in Django admin

I want to display different form fields for add and change view in Django admin.

If it is add then I am showing the form field file_upload and if it is change then I am showing model fields cname and mname

Code from admin.py

class couplingAdmin(admin.ModelAdmin):
    list_display = ('cname','mname')
    form = CouplingUploadForm #upload_file is here

    def get_form(self, request, obj=None, **kwargs):
        # Proper kwargs are form, fields, exclude, formfield_callback
        if obj: # obj is not None, so this is a change page
            kwargs['exclude'] = ['upload_file',]
        else: # obj is None, so this is an add page
            kwargs['exclude'] = ['cname','mname',]
        return super(couplingAdmin, self).get_form(request, obj, **kwargs)

If it is add then it's fine but if it is change view then I am getting all the fields ie cname,mname,upload_file.

Please suggest how can I remove upload_file from change view in admin.

Any help is highly appreciated. Thanks in advance.

Upvotes: 7

Views: 8749

Answers (3)

bubbassauro
bubbassauro

Reputation: 4279

To use an entirely different form to add/change:

class couplingAdmin(admin.ModelAdmin):
    list_display = ('cname','mname')

    def get_form(self, request, obj=None, change=None, **kwargs):
        if not obj:
            # Use a different form only when adding a new record
            return CouplingUploadForm

        return super().get_form(request, obj=obj, change=change, **kwargs)

Upvotes: 1

rahman asghari
rahman asghari

Reputation: 71

class couplingAdmin(admin.ModelAdmin):
    list_display = ('cname','mname')
    def get_fields(self, request, obj=None):
        if obj:
            fields=('upload_file',)
        else:
            fields =('cname','mname')
        return fields

Upvotes: 7

wencakisa
wencakisa

Reputation: 5958

You can override the add_view and change_view methods in your ModelAdmin:

class CouplingAdmin(admin.ModelAdmin):
    list_display = ('cname', 'mname')
    form = CouplingUploadForm  # upload_file is here

    def add_view(self, request, extra_content=None):
        self.exclude = ('cname', 'mname')
        return super(CouplingAdmin, self).add_view(request)

    def change_view(self, request, object_id, extra_content=None):
        self.exclude = ('upload_file',)
        return super(CouplingAdmin, self).change_view(request, object_id)

Upvotes: 12

Related Questions