Question

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)
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top