如何在Django Admin中允许HTMLField并在模板上反映出来?

时间:2018-03-03 08:57:22

标签: python html django

我有一个使用此模型的Django应用程序:

class Dorm(models.Model):
    dorm_name = models.CharField(max_length=50, help_text="Enter dorm name")
    dorm_description = models.TextField(max_length=1000, help_text="Enter dorm description")

此模型已添加到Django Admin:

class DormAdmin(admin.ModelAdmin):
    list_display = ('dorm_name','dorm_room_count','dorm_caretaker','dorm_contact_no','dorm_availability')
    list_filter = ('dorm_room_count','dorm_caretaker','dorm_availability','dorm_date_added')

    fieldsets = (
       (None, {'fields': ('dorm_name', 'dorm_description', 'dorm_primary_picture', 'dorm_room_count')}),
       ('Contact Details', {'fields': ('dorm_address','dorm_caretaker','dorm_contact_no','dorm_contact_email')}),
       ('Date',{'fields': ('dorm_date_added','dorm_availability','dorm_date_updated')}),
       ('Others',{'fields': ('dorm_house_rules',)}),
    )

我在模板中使用了这个dorm_description:

<div class="amenities">
    <div class="titlediv">About this dorm</div>
    <h5 class="padding-bottom">{{ dorm.dorm_description }}</h5>
</div>

但是,在模板中,它没有像我在Django Admin中那样显示换行符。它包装了一切并忽略了换行符。有人可以帮忙吗?

以下是截图:

Django App Display:enter image description here

Django管理员显示:enter image description here

1 个答案:

答案 0 :(得分:0)

尝试在您的文字中添加<br> html标记,并使用safe过滤器将文字字段渲染为纯HTML:

<h5 class="padding-bottom">{{ dorm.dorm_description|safe }}</h5>

请注意,在这种情况下,非管理员用户无权修改dorm_description以阻止xss attack