Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different fields for add and change pages in admin

I have a django app with the following class in my admin.py:

class SoftwareVersionAdmin(ModelAdmin):     fields = ("product", "version_number", "description",       "media", "relative_url", "current_version")     list_display = ["product", "version_number", "size",       "current_version", "number_of_clients", "percent_of_clients"]     list_display_links = ("version_number",)     list_filter = ['product',] 

I want to have these fileds for add page but different fields for change page. How can I do that?

like image 394
alexarsh Avatar asked Jun 12 '11 12:06

alexarsh


2 Answers

This is an old question but I wanted to add that the add_view and change_view methods can be modified for this purpose:

class SoftwareVersionAdmin(ModelAdmin):      ...      def add_view(self,request,extra_content=None):          self.exclude = ('product','version_number',)          return super(SoftwareVersionAdmin,self).add_view(request)       def change_view(self,request,object_id,extra_content=None):          self.exclude = ('product','description',)          return super(SoftwareVersionAdmin,self).change_view(request,object_id) 
like image 172
dpawlows Avatar answered Sep 23 '22 06:09

dpawlows


First have a look at source of ModelAdmin class' get_form and get_formsets methods located in django.contrib.admin.options.py. You can override those methods and use kwargs to get the behavior you want. For example:

class SoftwareVersionAdmin(ModelAdmin):     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'] = ['foo', 'bar',]         else: # obj is None, so this is an add page             kwargs['fields'] = ['foo',]         return super(SoftwareVersionAdmin, self).get_form(request, obj, **kwargs) 
like image 42
shanyu Avatar answered Sep 21 '22 06:09

shanyu