In the django admin I have a TabularInline for a ManyToMany field with a raw_id_fields set. It displays the unicode() of the object next to the html input field.
I would like it to display the an email link. So in the unicode() function of the model, I put in the html tags to 开发者_运维知识库create a link. However, it is displaying the html tags.
Is there a way to tell the admin that the unicode is safe to display tags?
I've tried using the allow_tags property but that seems to only be a ModelAdmin property.
Is it possible to do this without creating a new template?
EDIT:
I've found exactly where this is happening. On line 159 of:django/contrib/admin/widgets.py
return ' <strong>%s</strong>' % escape(truncate_words(obj, 14))
The escape there is manually escaping it. I've tested removing the escape() and it works. I don't like the idea of editing the django source. How could I get around this without change the source?
If your aim is to just display an email link for the list view, i would suggest writing a custom column for the list view like this:
list_display = ('admin_email', ...)
def admin_email(self, object):
return '<a href="%s">%s</a>'%(admin.email, admin)
admin_email.allow_tags = True
admin_email.short_description = 'Send Email'
This is better because you might be using the unicode call at a lot of other places, and the html might cause problems there.
Here is an example, with same end result as sebpiq's using SafeUnicode
, "A unicode subclass that has been specifically marked as 'safe' for HTML output purposes."
e.g.
from django.utils.safestring import SafeUnicode
class SomeClass(models.Model):
...
def __unicode__(self):
return SafeUnicode("foo: %s<br>bar: %s" % (foo, bar))
You should try mark_safe on the value that you return. Then the string shouldn't be escaped anymore !
精彩评论