gpt4 book ai didi

python - Django 将错误列表输出为字符串而不是 html

转载 作者:行者123 更新时间:2023-12-01 13:11:49 25 4
gpt4 key购买 nike

我正在尝试自定义 django 中的默认错误列表。我试过关注 the docs ,但问题是假设的 html 被输出为文本而不是 html: enter image description here

我不太确定为什么会这样,因为代码几乎是从文档中复制粘贴的。代码:

表格.py

class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()

def as_divs(self):
if not self: return ''
return '<div class="test">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])

View .py

def addUser(request):    
add_user_form = AddUserForm()
messages.warning(request, 'message')

if request.method == 'POST':
add_user_form = AddUserForm(request.POST, error_class=DivErrorList)

if add_user_form.is_valid():
user = add_user_form.save()
customer_group = Group.objects.get(name = 'group_name')
user.roles.add(customer_group)
messages.success(request, 'message')
return redirect('users')

else:
messages.error(request, 'message')

context = {
'add_user_form': add_user_form,
}

return render(request, 'users/backend/user/user_add.html', context)

html

<div class="w-full mt-6">
{% include 'components/typography/form_label.html' with label='Gjenta passord' %}
{{ add_user_form.password2 }}
{{ add_user_form.password2.errors }}
</div>

最佳答案

您需要将字符串标记为“安全”,即:

return '<div class="test">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])

应该是

return mark_safe('<div class="test">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self]))

mark_safe 的来源:

from django.utils.safestring import mark_safe

关于python - Django 将错误列表输出为字符串而不是 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com