Written Written - 4 months ago 18
HTML Question

Alternative way to return HTML as a read only field on the Django Admin

I have a Django admin class that contains a read only field which returns a table in HTML with 2 different links. The first link loads the page of all payments the user has sent, the second loads the page of all payments the user has received. In order to create this functionality, there is a need to return a lot of HTML. Is there an alternative to simply returning it?

Here is my current relevant code:

class UserAdmin(SimpleHistoryAdmin):
readonly_fields = ('payment_history')

def payment_history(self, obj):
return "<table style='border: none'>" \
"<tr><td><a href='/admin/payment/payment/?sender__id=%s'>Sent by this user</a></td>" \
"<td><a href='/admin/payment/payment/?receiver__id=%s'>Sent to this user</a></td>" \
"</tr></table>" % (obj.id, obj.id)
payment_history.allow_tags = True


A preferred alternative would be having this code in a real HTML file that can be returned by the same method.

Answer

How about using render_to_string? https://docs.djangoproject.com/en/1.9/topics/templates/#django.template.loader.render_to_string

templates/myapp/payment_history.html:

<table style='border: none'>
  <tr>
     <td><a href='/admin/payment/payment/?sender__id={{object.id}}'>Sent by this user</a></td>
    <td><a href='/admin/payment/payment/?receiver__id={{object.id}}'>Sent to this user</a></td>
  </tr>
</table>

admin.py:

from django.template.loader import render_to_string

class UserAdmin(SimpleHistoryAdmin):
    readonly_fields = ('payment_history')

    def payment_history(self, obj):
    return render_to_string('myapp/payment_history.html', {'object':obj})
Comments