Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Read only field

How do I allow fields to be populated by the user at the time of object creation ("add" page) and then made read-only when accessed at "change" page?

like image 393
natasha Avatar asked Apr 14 '10 17:04

natasha


1 Answers

The simplest solution I found was to override the get_readonly_fields function of ModelAdmin:

class TestAdmin(admin.ModelAdmin):    
    def get_readonly_fields(self, request, obj=None):
        '''
        Override to make certain fields readonly if this is a change request
        '''
        if obj is not None:
            return self.readonly_fields + ('title',)
        return self.readonly_fields
admin.site.register(TestModel, TestAdmin)

Object will be none for the add page, and an instance of your model for the change page. Edit: Please note this was tested on Django==1.2

like image 107
warren Avatar answered Sep 17 '22 17:09

warren