从Django表单序列化 [英] Serialize from a Django form

查看:94
本文介绍了从Django表单序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个传统的django站点迁移到一个API Restful。



我有一个很大的表单已经在工作。此表单目前是一个Django.forms.Form 对象,我想将其发送到一个休息的API点。



我想做一些类似于 ModelSerializer ,但是从Form对象而不是Model。



此项目有一些形式(不是基于模型),我想重用这个代码。



令人遗憾的是,我没有发现如何直接从Form进行序列化。



示例I想要做



  class LargeAndUgglyForm(forms.Form):

email = forms.CharField(
required = True,
max_length = 100,
widget = forms.TextInput(
attrs = {
'placeholder':_('Correoelectrónico')}))

password1 = forms.CharField(required = True,widget = forms.PasswordInput(
attrs = {'placeholder':_(u'Contraseña')}))

password2 = forms.CharField(required = True,widget = forms.PasswordInput(
attrs = {'placeholde r':_(u'Repetircontraseña')}))

name_company = forms.CharField(
required = True,
max_length = 100,
widget = forms.TextInput(
attrs = {
'placeholder':_('Nombre de la Empresa')}))

#...和更多的字段


class SignupSerializer(???):
Meta:
form = LargeAndUgglyForm

def create(self,validated_data):

form_instance = LargeAndUgglyForm(validated_data)

如果form_instance.is_valid():
#...

PS。对不起我的英语

解决方案

嗯,我收到一个朋友的回复,他给了我:



https:// django-rest-framework-braces.readthedocs.io/en/latest/overview.html#formserializer


I'm migrating a tradicional django-site to a API Restful.

I have a large form already working. This form is currently a Django.forms.Form object, and I want to send it's submit to a rest API point.

I want to do some similar to ModelSerializer but from the Form object instead a Model.

This project has some forms (not model based) and I want to reuse this code.

Regrettably I don't found how to do a serializer directly from Form.

Example I want to do

class LargeAndUgglyForm(forms.Form):

    email = forms.CharField(
        required=True,
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'placeholder': _('Correo electrónico')}))

    password1 = forms.CharField(required=True, widget=forms.PasswordInput(
        attrs={'placeholder': _(u'Contraseña')}))

    password2 = forms.CharField(required=True, widget=forms.PasswordInput(
        attrs={'placeholder': _(u'Repetir contraseña')}))

    name_company = forms.CharField(
        required=True,
        max_length=100,
        widget=forms.TextInput(
            attrs={
                'placeholder': _('Nombre de la Empresa')}))

    # ... and much more fields


class SignupSerializer(???):
    Meta:
        form = LargeAndUgglyForm

    def create(self, validated_data):

        form_instance = LargeAndUgglyForm(validated_data)

        if form_instance.is_valid():
            # ...

PS. Sorry my english

解决方案

Well, I received a response from a friend, and he gave me it:

https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#formserializer

这篇关于从Django表单序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆