Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think that agf's solution is pretty awesome -- lots of kudos to him. But I needed a couple more features:</p> <ul> <li>to be able to have multiple links for one admin</li> <li>to be able to link to model in different app</li> </ul> <p>Solution:</p> <pre><code>def add_link_field(target_model = None, field = '', app='', field_name='link', link_text=unicode): def add_link(cls): reverse_name = target_model or cls.model.__name__.lower() def link(self, instance): app_name = app or instance._meta.app_label reverse_path = "admin:%s_%s_change" % (app_name, reverse_name) link_obj = getattr(instance, field, None) or instance url = reverse(reverse_path, args = (link_obj.id,)) return mark_safe("&lt;a href='%s'&gt;%s&lt;/a&gt;" % (url, link_text(link_obj))) link.allow_tags = True link.short_description = reverse_name + ' link' setattr(cls, field_name, link) cls.readonly_fields = list(getattr(cls, 'readonly_fields', [])) + \ [field_name] return cls return add_link </code></pre> <p>Usage:</p> <pre><code># 'apple' is name of model to link to # 'fruit_food' is field name in `instance`, so instance.fruit_food = Apple() # 'link2' will be name of this field @add_link_field('apple','fruit_food',field_name='link2') # 'cheese' is name of model to link to # 'milk_food' is field name in `instance`, so instance.milk_food = Cheese() # 'milk' is the name of the app where Cheese lives @add_link_field('cheese','milk_food', 'milk') class FoodAdmin(admin.ModelAdmin): list_display = ("id", "...", 'link', 'link2') </code></pre> <p>I am sorry that the example is so illogical, but I didn't want to use my data.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload