通过解析yaml文件创建表单

utk*_*sal 2 django pyyaml wtforms flask-wtforms

我有一个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
Run Code Online (Sandbox Code Playgroud)

我想要做的是解析此文件以创建一个表单类(可由 Django 或 WT-Forms 使用)来创建 Web 表单。

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

我目前正在尝试使用 pyyaml 来完成此任务。在此先感谢您的帮助。

Bra*_*don 6

您需要做的就是将数据传递到表单类并覆盖__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})
Run Code Online (Sandbox Code Playgroud)

只要您检查适当的“property_type”,您就不需要更新表单类。如果您向 yaml 添加新字段,表单将反映该字段。