通过解析yaml文件来创建表单

时间:2015-03-10 13:38:48

标签: django wtforms flask-wtforms pyyaml

我有一个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使用)来创建Web表单。

我不能简单地创建类,因为每当yaml配置文件更新时,表单(以及类)都需要自动更新。

我目前正在尝试使用pyyaml来实现这一目标。 在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您需要做的就是将数据传递到表单类并覆盖__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添加新字段,表单将反映该字段。