How to Pass Extra Context Data to Serializers in Django-Rest-Framework

read_only, write_only, required, default, initial, source,
label, help_text, style, error_messages, allow_empty,
instance, data, partial, context, allow_null
from rest_framework import  serializersclass SendEmailSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
def validate_email(self, email):
# .....
exclude_email_list = self.context.get("exclude_email_list", [])
if email in exclude_email_list:
raise serializers.ValidationError("We cannot send an email to this user")
# .....
return email
# Passing the extra context data to serializers in FBV style.
from rest_framework.decorators import api_view
from your_app.serializers import SendEmailSerializer
@api_view(['POST'])
def send_email_view(request):
# .....
context = {"exclude_email_list": ['test@test.com', 'test1@test.com']}
serializer = SendEmailSerializer(data=request.data, context=context)
# ....
# Passing the extra context data to serializers in generic CBV or ViewSets style
#ViewSets
from rest_framework import viewsets
class SendEmailViewSet(viewsets.GenericViewSet):
# ......
def get_serializer_context(self):
context = super(CommentViewSet, self).get_serializer_context()
context.update({
"exclude_email_list": ['test@test.com', 'test1@test.com']
# extra data
})
return context
# .......
#Generic Views
from rest_framework import generics
class SendEmailView(generics.GenericAPIView):
# ......
def get_serializer_context(self):
context = super(CommentViewSet, self).get_serializer_context()
context.update({
"exclude_email_list": ['test@test.com', 'test1@test.com']
# extra data
})
return context
# .......

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store