Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different form fields for add and change view in Django admin

Tags:

python

django

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.

like image 952
Prithviraj Mitra Avatar asked Dec 10 '22 10:12

Prithviraj Mitra


1 Answers

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)
like image 140
wencakisa Avatar answered May 11 '23 16:05

wencakisa