Skip to content

Commit

Permalink
Added uneditable_exiting chapter
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 19, 2018
1 parent c1a3766 commit 51ce3d4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions docs/uneditable_existing.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,14 @@
How to make a field editable while creating, but read only in existing objects?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

YOu need to make the :code:`name` and :code:`category` read only once a :code:`Hero` is created. However duing the first write the fields needs to be editable.

You can do this by overriding :code:`get_readonly_fields` method, like this::

def get_readonly_fields(self, request, obj=None):
if obj:
return ["name", "category"]
else:
return []

:code:`obj` is None during the object creation, but set to the object being edited during an edit.
6 changes: 6 additions & 0 deletions heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):

exclude = ['added_by',]

def get_readonly_fields(self, request, obj=None):
if obj:
return ["name", "category"]
else:
return []

def save_model(self, request, obj, form, change):
if not obj.pk:
# Only set added_by during the first save.
Expand Down

0 comments on commit 51ce3d4

Please sign in to comment.