Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework how to make model serializer fields required

I have a model that I'm filling out step by step, it means I'm making a form wizard.

Because of that most fields in this model are required but have null=True, blank=True to avoid raising not null errors when submitting part of the data.

I'm working with Angular.js and django-rest-framework and what I need is to tell the api that x and y fields should be required and it needs to return a validation error if they're empty.

like image 678
Cristian Rojas Avatar asked Jun 20 '15 11:06

Cristian Rojas


People also ask

How do you make a field optional in a serializer?

You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly. Update for REST framework 3.0 serializer. fields can be modified on an instantiated serializer.

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.

How do you pass extra context data to Serializers in Django REST framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.


1 Answers

The best option according to docs here is to use extra_kwargs in class Meta, For example you have UserProfile model that stores phone number and is required

class UserProfileSerializer(serializers.ModelSerializer):     class Meta:         model = UserProfile         fields = ('phone_number',)         extra_kwargs = {'phone_number': {'required': True}}  
like image 117
Sandeep Patil Avatar answered Oct 02 '22 17:10

Sandeep Patil