Django 1.4: return HTML in function
如何在Django 1.4中的函数中返回将被解释的HTML标记?
1 2 3 4 5 | class MyModel(models.Model): my_attribute = models.CharField(max_length=50) def my_link(self): return 'google' |
想象一下,我有一个带有my_link方法的模型。在我的管理界面中,我想显示列
自Django 1.5起,模块
编辑
myapp.admin.py
1 2 3 4 5 6 7 | 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) |
设置
1 2 3 4 5 6 | class MyModel(models.Model): my_attribute = models.CharField(max_length=50) def my_link(self): return 'google' my_link.allow_tags = True # <--- |
根据
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.