A allow_tags link generator in the Django Admin

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Example
========

::

  class InboxMessageAdmin(admin.ModelAdmin):                                                                                                                                          
      list_display = (
          '__unicode__', "_link_inbox", "_link_message", 'read', 'read_date', "ctime", "utime", )
      list_filter = ("ctime", "utime", "read", )
      list_editable = ("read",)
      date_hierarchy = 'ctime'
      list_per_page = 50
  link_generator(InboxMessageAdmin, "_link_inbox", ["inbox"])
  link_generator(InboxMessageAdmin, "_link_message", ["message"])

"""
from django.core.urlresolvers import reverse                                                                                                                                        


def link_generator(klass, method_name, attr):
    """ link generator """
    def method(self, obj):
        app_name = obj.__module__.split(".")[0]
        rel_obj = obj
        for a in attr:
            rel_obj = getattr(obj, a)
        model_name = rel_obj.__class__.__name__.lower()
        primary_id = rel_obj.id

        url = reverse('admin:{0}_{1}_changelist'.format(app_name, model_name))
        try:
            return u"<a href='{0}?id__exact={1}'/>{2}.{3}</a>".format(
                url, primary_id, app_name, model_name)
        except KeyError:
            return
    method.allow_tags = True
    method.short_description = method_name
    setattr(klass, method_name, method)

More like this

  1. Django admin autoregister by Mimino 5 months, 1 week ago
  2. Link raw_id_fields (both ForeignKeys and ManyToManyFields) to their change pages by EmilStenstrom 3 years, 6 months ago
  3. newforms-admin edit callback-url hook by myers 6 years ago
  4. Admin Save and view next button html by ungenio41 3 years, 11 months ago
  5. URLField admin widget with View Link button by ungenio41 3 years, 11 months ago

Comments

(Forgotten your password?)