通过解析yaml文件创建表单
Create a form by parsing yaml file
我有一个yaml文件如下
name:
property_type: string
mandatory: True
default: None
help: your full name
address:
city:
property_type: string
mandatory: True
default: None
help: city
state:
property_type: string
mandatory: True
default: None
help: state
我想做的是解析此文件以创建表单 class(可由 Django 或 WT-Forms 使用)来创建 Web 表单。
我不能简单地制作 class 因为表单(因此 class)需要在更新 yaml 配置文件时自动更新。
我目前正在尝试使用 pyyaml 来完成此操作。
在此先感谢您的帮助。
您需要做的就是将数据传递到表单 class 并覆盖 __init__
以添加您需要的字段:
# PSEUDO CODE - don't just copy and paste this
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.field_data = kwargs.pop('field_data')
super(MyForm, self).__init__(*args, **kwargs)
# assuming a list of dictionaries here...
for field in field_data:
if field['property_type'] == 'string':
self.fields[field['name']] = forms.CharField(
max_length=field['max_length'], help_text=field['help'],
required=field['mandatory'], initial=field['default'])
elif field['property_type'] == 'something else':
# add another type of field here
# example use in a view
def my_view(request):
field_data = parse_yaml('some-file.yml')
form = MyForm(field_data=field_data)
if request.method == 'POST':
if form.is_valid():
form.save() # you need to write this method
return render(request, 'your-template.html', {'form': form})
只要您正在检查合适的 "property_type",您就不需要更新您的表单 class。如果向 yaml 添加新字段,表单将反映该字段。
我有一个yaml文件如下
name:
property_type: string
mandatory: True
default: None
help: your full name
address:
city:
property_type: string
mandatory: True
default: None
help: city
state:
property_type: string
mandatory: True
default: None
help: state
我想做的是解析此文件以创建表单 class(可由 Django 或 WT-Forms 使用)来创建 Web 表单。
我不能简单地制作 class 因为表单(因此 class)需要在更新 yaml 配置文件时自动更新。
我目前正在尝试使用 pyyaml 来完成此操作。 在此先感谢您的帮助。
您需要做的就是将数据传递到表单 class 并覆盖 __init__
以添加您需要的字段:
# PSEUDO CODE - don't just copy and paste this
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.field_data = kwargs.pop('field_data')
super(MyForm, self).__init__(*args, **kwargs)
# assuming a list of dictionaries here...
for field in field_data:
if field['property_type'] == 'string':
self.fields[field['name']] = forms.CharField(
max_length=field['max_length'], help_text=field['help'],
required=field['mandatory'], initial=field['default'])
elif field['property_type'] == 'something else':
# add another type of field here
# example use in a view
def my_view(request):
field_data = parse_yaml('some-file.yml')
form = MyForm(field_data=field_data)
if request.method == 'POST':
if form.is_valid():
form.save() # you need to write this method
return render(request, 'your-template.html', {'form': form})
只要您正在检查合适的 "property_type",您就不需要更新您的表单 class。如果向 yaml 添加新字段,表单将反映该字段。