Skip to content

Commit

Permalink
Added admin change url chapter
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 20, 2018
1 parent e1d53ed commit 5687321
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/many_to_many.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ You will see a column for children like this:

.. image:: related_fk_display.png

You can use the same method for M2M relations as well.
You can use the same method for M2M relations as well. You should also read :doc:`object_url`.
25 changes: 25 additions & 0 deletions docs/object_url.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,27 @@
How to get Django admin urls for specific objects?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

You have a children column displatying the names of each heroes' children. You have been asked to link each children to the change page. You can do it like this.::

@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...

def children_display(self, obj):
display_text = ", ".join([
"<a href={}>{}</a>".format(
reverse('admin:{}_{}_change'.format(obj._meta.app_label, obj._meta.model_name),
args=(child.pk,)),
child.name)
for child in obj.children.all()
])
if display_text:
return mark_safe(display_text)
return "-"

The :code:`reverse('admin:{}_{}_change'.format(obj._meta.app_label, obj._meta.model_name), args=(child.pk,))`, gives the change url for an object.

The other options are

* Delete: reverse('admin:{}_{}_delete'.format(obj._meta.app_label, obj._meta.model_name), args=(child.pk,))
* History: reverse('admin:{}_{}_history'.format(obj._meta.app_label, obj._meta.model_name), args=(child.pk,))
13 changes: 10 additions & 3 deletions heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import sys
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.safestring import mark_safe
from django.urls import path
from django.urls import path, reverse


class IsVeryBenevolentFilter(admin.SimpleListFilter):
Expand Down Expand Up @@ -73,9 +73,16 @@ def headshot_image(self, obj):

def children_display(self, obj):
display_text = ", ".join([
child.name for child in obj.children.all()
"<a href={}>{}</a>".format(
reverse('admin:{}_{}_change'.format(obj._meta.app_label, obj._meta.model_name),
args=(child.pk,)),
child.name)
for child in obj.children.all()
])
return display_text or "-"
if display_text:
return mark_safe(display_text)
return "-"

children_display.short_description = "Children"

# def get_readonly_fields(self, request, obj=None):
Expand Down

0 comments on commit 5687321

Please sign in to comment.