编写动态表单渲染的自定义模板标签与过滤器
基于JSON schema动态生成表单HTML,并支持复杂嵌套布局。 · 难度:入门 · +10XP
JSON Schema驱动的表单渲染器
本教程不教你写forms.py,而是用自定义模板标签解析JSON schema生成任意表单。例如:传入一个包含field类型(text, select, checkbox)、验证规则、布局(row/column)的JSON对象,模板标签输出完整的Bootstrap表单。同时包含过滤标签用于格式化错误信息。你将学习如何利用template.Library和Node类实现带参数的标签,以及解析器如何访问上下文。
from django import template
import json
register = template.Library()
@register.simple_tag(takes_context=True)
def dynamic_form(context, schema_json):
schema = json.loads(schema_json)
html = ''
for field in schema['fields']:
if field['type'] == 'text':
html += f''
elif field['type'] == 'select':
choices = ''.join([f'' for c in field['choices']])
html += f''
return html