Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize from a Django form

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

like image 634
Exos Avatar asked Sep 04 '16 07:09

Exos


People also ask

What is serialization in Django?

Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).

Is serialization necessary in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.

How do I serialize Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

What is deserializer in Django?

deserialize is for deserializing a particular type of JSON - that is, data that was serialized from model instances using serializers.


1 Answers

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

like image 131
Exos Avatar answered Nov 24 '22 22:11

Exos