Override the get_renderer_context
method on your ViewSet (as already suggested):
def get_renderer_context(self):
context = super().get_renderer_context()
context['foo'] = 'bar'
return context
Subclass TemplateHTMLRenderer
, but only override the get_template_context
method instead of the entire render method (render calls self.get_template_context
to retrieve the final context to pass to the template):
class ModifiedTemplateHTMLRenderer(TemplateHTMLRenderer): def get_template_context(self, data, renderer_context): "" " Override of TemplateHTMLRenderer class method to display extra context in the template, which is otherwise omitted. "" " response = renderer_context['response'] if response.exception: data['status_code'] = response.status_code return data else: context = data # pop keys which we do not need in the template keys_to_delete = ['request', 'response', 'args', 'kwargs'] for item in keys_to_delete: renderer_context.pop(item) for key, value in renderer_context.items(): if key not in context: context[key] = value return context
ViewSet:
class LanguageViewSet(viewsets.ModelViewSet):
queryset = Language.objects.all()
serializer_class = LanguageSerializer
filter_backends = (filters.DjangoFilterBackend, )
filter_fields = ('name', 'active')
def get_serializer_context(self):
context = super().get_serializer_context()
context['foo'] = 'bar'
return context
Serializer:
class YourSerializer(serializers.Serializer):
field = serializers.CharField()
def to_representation(self, instance):
ret = super().to_representation(instance)
# Access self.context here to add contextual data into ret
ret['foo'] = self.context['foo']
return ret
Another way to achieve this, in case you don't wish to mess with your serializers, would be to create a custom TemplateHTMLRenderer.
class TemplateHTMLRendererWithContext(TemplateHTMLRenderer): def render(self, data, accepted_media_type = None, renderer_context = None): # We can 't really call super in this case, since we need to modify the inner working a bit renderer_context = renderer_context or {} view = renderer_context.pop('view') request = renderer_context.pop('request') response = renderer_context.pop('response') view_kwargs = renderer_context.pop('kwargs') view_args = renderer_context.pop('args') if response.exception: template = self.get_exception_template(response) else: template_names = self.get_template_names(response, view) template = self.resolve_template(template_names) context = self.resolve_context(data, request, response, render_context) return template_render(template, context, request = request) def resolve_context(self, data, request, response, render_context): if response.exception: data['status_code'] = response.status_code data.update(render_context) return data
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.,The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.,Repeated logic can be combined into a single class. In the above example, we only need to specify the queryset once, and it'll be used across multiple views.,Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
Let's define a simple viewset that can be used to list or retrieve all the users in the system.
from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): "" " A simple ViewSet for listing or retrieving users. "" " def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many = True) return Response(serializer.data) def retrieve(self, request, pk = None): queryset = User.objects.all() user = get_object_or_404(queryset, pk = pk) serializer = UserSerializer(user) return Response(serializer.data)
If we need to, we can bind this viewset into two separate views, like so:
user_list = UserViewSet.as_view({
'get': 'list'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve'
})
Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
from myapp.views
import UserViewSet
from rest_framework.routers
import DefaultRouter
router = DefaultRouter()
router.register(r 'users', UserViewSet, basename = 'user')
urlpatterns = router.urls
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
class UserViewSet(viewsets.ViewSet): "" " Example empty viewset demonstrating the standard actions that will be handled by a router class. If you 're using format suffixes, make sure to also include the `format=None` keyword argument for each action. "" " def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk = None): pass def update(self, request, pk = None): pass def partial_update(self, request, pk = None): pass def destroy(self, request, pk = None): pass
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the list
action similar to this:
def get_permissions(self): "" " Instantiates and returns the list of permissions that this view requires. "" " if self.action == 'list': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes]
Posted On 05 October 2017 By MicroPyramid
- Serializers are used to validate the data in Django rest framework.
- Generally, serializers provide basic validations based on the type of field. Model serializers use model validations(primary key, foreign key, unique, etc).
- We not only use these basic validations but also custom validations to some of the fields.
- For writing custom validations we may require some extra data in validation methods of serializers.
- Django Rest Framework Serializer takes the following parameters while creating the serializer object.
read_only, write_only, required,
default, initial, source,
label, help_text, style, error_messages, allow_empty,
instance, data, partial, context, allow_null
serializers.py
from rest_framework
import serializers
class 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
views.py
# 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 #.......
{
'request': self.request,
'format': self.format_kwarg,
'view': self
}
Django Rest Framework: Passing Context in Viewsets,Django Rest Framework passing context to Meta,Pass request context to serializer from Viewset in Django Rest Framework,Updating a model using Django Rest Framework and ViewSets
By default, request
is being sent to any Generic View and ViewSet. You can check the source code in GitHub as well. So you do not have to inject them in every view. If you want to pass extra context, then override get_serializer_context(...)
method:
class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
...
def get_serializer_context(self):
context = super().get_serializer_context()
context['custom_context'] = 'Your custom context'
return context