Django中render_to_string无法渲染field.help_text问题求助
Django表单help_text渲染异常排查求助
我开发了一款问卷应用,通过模型字段的help_text属性存储每个数据字段对应的问题,为此编写了以下自定义ModelForm:
class CustomModelForm(forms.ModelForm): """A customized ModelForm for Django. This class extends the base ModelForm class from Django's forms module. It provides additional functionality to handle errors and help text for form fields. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.errors: attrs = self[field].field.widget.attrs attrs.setdefault("class", "") attrs["class"] += " is-invalid" for field in self.fields: try: self.fields[field].help_text = self._meta.model._meta.get_field( field ).help_text except Exception: pass
另外,我还创建了模板标签及对应的HTML模板:
模板标签代码:
@register.inclusion_tag("../templates/snippets/radioInlineField.html") def render_radioInlineInput_field(formfield): return {"formfield": formfield}
对应的HTML模板代码:
{% with field=formfield %} <div class="col-sm-6 text-start"> {% if field.help_text %} <p class="mb-0">{{ field.help_text }}: </p> {% endif %} </div> <div class="col-sm-6 mt-0 "> {% for radio in field %} <div class="form-check form-check-inline"> {{ radio.tag }} <label class="form-check-label" for="id_{{ radio.id_for_label }}">{{ radio.choice_label }}</label> </div> {% endfor %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} </div> {% endwith %}
问题现象
正常情况下功能运行良好,但当同一视图中同时存在Form A(仅包含上述类型字段)和Form B(包含必填字段)时,若Form B验证失败,{{ field.help_text }}会停止渲染。
我将问题定位到Django的render函数:
def render( request, template_name, context=None, content_type=None, status=None, using=None ): """ Return an HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status)
调试发现,Form B验证失败后,context中仍然保留着正确的form.fields.field.help_text值,但经过render_to_string处理后,最终输出内容里就丢失了该值。
已尝试的无效方案
- 使用
field.help_text|safe过滤器 - 确认表单已将正确数据传递至
render_to_string()方法 - 完成了尽可能多的调试工作
请求各位提供问题排查的思路或提示。
内容的提问来源于stack exchange,提问作者NicoS
相关产品推荐
相关产品推荐

