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

问题描述 投票:0回答:1

我有一个这个模型的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

python html django
1个回答
0
投票

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

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

请注意,在这种情况下,非管理员用户不应该有权修改dorm_description以防止xss attack

© www.soinside.com 2019 - 2024. All rights reserved.