如何通过覆盖内置表单模板修改error_class样式化Django表单验证错误列表
如何通过覆盖内置表单模板修改error_class来样式化Django表单验证错误列表
通过调用模板引擎的TemplatesSetting()覆盖ErrorList的内置模板,即可自定义错误列表的HTML结构及样式,具体实现步骤如下:
1. 自定义ErrorList类
在表单所在的Python文件中定义自定义的ErrorList子类,指定错误类名和自定义模板路径:
from django.forms.renderers import TemplatesSetting from django.forms.utils import ErrorList from django import forms from .models import Offer class CustomErrorList(ErrorList): def __init__(self, initlist=None, error_class=None, renderer=None): super().__init__(initlist, error_class="list-group", renderer=TemplatesSetting()) template_name = "forms/errors/default.html" template_name_text = "forms/text.txt" template_name_ul = "forms/errors/ul.html" class OfferForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_class = CustomErrorList class Meta: model = Offer exclude = ['city', 'user', 'is_active', 'count_of_views', 'in_favorites']
2. 配置模板目录(settings.py)
确保项目的模板目录已正确配置,让Django能找到自定义的错误模板:
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
3. 编写错误列表模板文件
在项目模板目录下创建forms/errors/ul.html文件,自定义错误列表的HTML结构和样式(示例使用Bootstrap列表组样式):
{% if errors %}<ul class="list-group">{% for error in errors %}<li class="list-group-item text-white bg-danger">{{ error }}</li>{% endfor %}</ul>{% endif %}
注:若需要其他格式的错误展示(如纯文本、默认格式),可对应创建
forms/text.txt和forms/errors/default.html模板文件。
内容的提问来源于stack exchange,提问作者Kirill Meha
相关产品推荐
相关产品推荐

