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.
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.
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.
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.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With