在django.forms.Form和rest_framework.serializers之间是否有转换器?

时间:2016-12-21 20:26:20

标签: django django-rest-framework

我的django 1.9项目中已经定义了很多表单。现在我需要将它们导出为REST(DRF 3.5.3)。

通过一点点黑客攻击,我能够提供GET和PUT方法。但我还需要提供OPTIONS方法,而且我似乎无法找到任何可以帮助我做到这一点的方法。

那么,是否存在将实例化表单转换为DRF Serializer / ViewSet的内容?

2 个答案:

答案 0 :(得分:1)

不,但您可以按照http://www.django-rest-framework.org/topics/html-and-forms/#rendering-forms中的说明进行相反的操作。

答案 1 :(得分:0)

我不想在表单中弄乱我的所有自定义逻辑,所以我只添加了as_options方法:

class APIViewForm(Form):

    def as_dict(self):
        return {fld.auto_id: self.initial.get(fld.name, None) for fld in self}

    def as_options(self):
        flds = {}
        for fld in self:
            flds[fld.name] = f = {}
            fld = fld.field
            f.update(dict(
                required=fld.required,
                read_only=fld.disabled,
                label=fld.label,
            ))
            if isinstance(fld, (CharField, URLField)):
                f['type'] = 'field'
                if fld.max_length:
                    f['max_length'] = fld.max_length
                if fld.min_length:
                    f['min_length'] = fld.min_length
            elif isinstance(fld, IntegerField):
                f['type'] = 'integer'
                if fld.max_value:
                    f['max_value'] = fld.max_value
                if fld.min_value:
                    f['min_value'] = fld.min_value
            elif isinstance(fld, ChoiceField):
                f['type'] = 'choice'
                f['choices'] = [dict(value=c[0], display_name=c[1]) for c in fld.choices]
            elif isinstance(fld, DateTimeField):
                f['type'] = 'datetime'

        return dict(
            name=self.__class__.__qualname__,
            description='',
            renders=['application/json'],
            parses=['application/json'],
            actions=dict(PUT=flds)
        )

似乎可以解决这个问题