3

How can I return a HTML Tag, which will be interpreted, in a function in Django 1.4?

class MyModel(models.Model):
    my_attribute = models.CharField(max_length=50)

    def my_link(self):
        return '<a href=google.com>google</a>'

Imagine I have this Model with the method my_link. In my Admin interface I want to display the columns my_attribute and my_link. But the problem is, that the html-Tag won't be interpreted. It just prints the text.

Since Django 1.5 there is the method format_html() in the module django.utils.html. But I need something similar in Django 1.4

EDIT
myapp.admin.py

from django.contrib import admin
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ['my_attribute', 'my_link']

admin.site.register(MyModel, MyModelAdmin)
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
0xAffe
  • 1,156
  • 1
  • 13
  • 29

1 Answers1

1

Set allow_tags attribute:

class MyModel(models.Model):
    my_attribute = models.CharField(max_length=50)

    def my_link(self):
        return '<a href=google.com>google</a>'
    my_link.allow_tags = True # <---

According to ModelAdmin.list_display documentation:

If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. If you’d rather not escape the output of the method, give the method an allow_tags attribute whose value is True. However, to avoid an XSS vulnerability, you should use format_html() to escape user-provided inputs.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    I tried this already. It doesn't work for me. Still the same behavior – 0xAffe Jan 15 '14 at 09:02
  • thank you! I just found the same solution in this (http://stackoverflow.com/questions/3298083/prevent-django-admin-from-escaping-html) post. – 0xAffe Jan 15 '14 at 09:15