我有一个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
我想做的是解析这个文件来创建一个表单类(可以被 Django 或 WT-Forms 使用)来创建网络表单。
我不能简单地创建类,因为只要更新 yaml 配置文件,表单(以及类)就需要自动更新。
我目前正在尝试使用 pyyaml 来完成此操作。 预先感谢您的帮助。
最佳答案
您需要做的就是将数据传递给表单类并覆盖 __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”,就不需要更新您的表单类。如果您向 yaml 添加新字段,表单将反射(reflect)该字段。
关于django - 通过解析yaml文件创建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28965281/