Skip to content

Commit

Permalink
Added readonly field chapter
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 19, 2018
1 parent 0234b64 commit 56ca88d
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 6 deletions.
Binary file added docs/changeview_readonly.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions docs/changeview_readonly.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,15 @@
How to mark a field as readonly in admin?
++++++++++++++++++++++++++++++++++++++++++

UMSRA has temporarily decided to stop tracking the family trees of mythological entities. You have been asked to make the :code:`father`, :code:`mother` and :code:`spouse` fields readonly.

You can do this by::

@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
readonly_fields = ["father", "mother", "spouse"]

Your create form looks like this:

.. image::changeview_readonly.png
Binary file added docs/uneditable_existing.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/uneditable_existing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ You can do this by overriding :code:`get_readonly_fields` method, like this::
else:
return []

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

exclude = ['added_by',]

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

# 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:
Expand Down

0 comments on commit 56ca88d

Please sign in to comment.