Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid code duplication in Django Forms and Django Rest Framework Serializers?

I work on a Django 1.8 project that must expose both a traditional HTML front-end and a JSON API. For the API we're using Django Rest Framework. Having worked with Rails, I try to follow the "Fat Models" pattern and place as much validation as humanly possible in the model and away from the form. Sometimes, however, there is custom validation that must be done at form level.

Example: I have a Image model that has a GenericForeignKey field and can potentially be related to any model in the system. These images also have a profile (e.g. 'logo', 'banner', etc). Depending on the profile, I need to do different validation. In principle I'd just create different form classes for different profiles, but it should also be possible to assign images to objects through the API. How can I avoid duplicating this custom validation both in Forms and Serializers?

like image 696
Ariel Avatar asked Sep 27 '22 07:09

Ariel


People also ask

Do we need Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What are Serializers explain Modelserializers?

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model.

What does serializer Is_valid do?

it validates your serializer with the condition of respective field specified in your serializer MessageSerializer .


1 Answers

I typically do this in my serializer:

def validate(self, attrs):
    # custom serializer validation

    self.myform = self.myform_class(
        data=attrs
    }

    if not self.myform.is_valid():
        raise serializers.ValidationError()
    return attrs

This way I can reuse form validation and add custom serializer validation at the same time + use both of builtin validators.

Let me know if this helps and if not maybe you can throw some code snippets, so we can figure out your exact case.

like image 151
mariodev Avatar answered Oct 12 '22 01:10

mariodev