问题描述
我有一个使用as_crispy_field templatetag呈现的字段
{{ form.field|as_crispy_field }}
我想将帮助文本的位置更改为红色标签
这是当前输出:
我希望它类似于以下内容:
解决方法
我已经通过覆盖crispy_forms模板来解决此问题。
通过查看crispy_forms模板crispy_forms/templates的结构,我发现他们从文件夹 crispy_forms / templates / {{TEMPLATE_PACK}} 中读取格式 例如crispy_forms/templates/bootstrap4
我决定创建自己的自定义文件夹来更改该字段的布局,并将其放置在项目的模板文件夹下。
在该文件夹中添加一个名为“ field.html”的文件;因此,读取格式会变得多么清晰,并更改了我想要自定义的内容。
自定义文件templates/bootstrap4/field.html
更改后的行(templates/bootstrap4/field.html上的第13-17行)
{% if field.label and not field|is_checkbox and form_show_labels %}
<label for="{{ field.id_for_label }}" class="{% if 'form-horizontal' in form_class %}col-form-label {% endif %}{{ label_class }}{% if field.field.required %} requiredField{% endif %}">
{{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</label>
{% comment %} ---------- Customization starts here ---------- {% endcomment %}
<strong style="color: red; font-size:14px">
<i>{{field.help_text|safe}}</i>
</strong>
{% comment %} ---------- Customization ends here ---------- {% endcomment %}
{% endif %}
字段错误处理(templates/bootstrap4/field.html上的第41-44行)
<div class="{{ field_class }}">
{% crispy_field field %}
{% comment %} ---------- Error handling starts here ---------- {% endcomment %}
{% if error_text_inline %}
{% include 'bootstrap4/layout/field_errors.html' %}
{% else %}
{% include 'bootstrap4/layout/field_errors_block.html' %}
{% endif %}
{% comment %} ---------- Error handling ends here ---------- {% endcomment %}
</div>
并修改模板中的字段以从新文件夹中读取
{{ form.myField|as_crispy_field:"custom_crispy_folder" }}