This repository has been archived on 2022-09-23. You can view files and clone it, but cannot push or open issues or pull requests.
webdev/api/snippets/views.py

37 lines
1.3 KiB
Python
Raw Normal View History

2022-01-08 00:40:31 +01:00
from django.contrib.auth.models import User
2022-01-08 00:12:34 +01:00
from .models import Snippet
2022-01-08 00:40:31 +01:00
from .serializers import SnippetSerializer, UserSerializer
2022-01-08 05:27:26 +01:00
from snippets.permissions import IsOwnerOrReadOnly
from rest_framework import permissions, renderers
2022-01-08 02:19:47 +01:00
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
2022-01-08 02:19:47 +01:00
class SnippetViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
2022-01-08 00:12:34 +01:00
Additionally we also provide an extra `highlight` action.
"""
2022-01-08 00:29:57 +01:00
queryset = Snippet.objects.all()
2022-01-08 00:40:31 +01:00
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly]
2022-01-08 00:40:31 +01:00
@action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs):
2022-01-08 02:19:47 +01:00
snippet = self.get_object()
return Response(snippet.highlighted)
2022-01-08 00:40:31 +01:00
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `retrieve` actions.
"""
2022-01-08 00:40:31 +01:00
queryset = User.objects.all()
serializer_class = UserSerializer