Skip to content

5. Views

Carlos Aguilar edited this page May 16, 2018 · 1 revision

/testapi/quickstart/views.py

class UserViewSet(viewsets.ModelViewSet):
    authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class PointViewSet(viewsets.ModelViewSet):
    queryset = Point.objects.all()
    serializer_class = PointSerializer

Rather than writing multiple views, we're grouping together all the common behavior into classes called ViewSets, in this particular case, we're using ModelViewSet.

The ModelViewSet provides the actions listed below:

  • .list()
  • .retrieve()
  • .create()
  • .update()
  • .partial_update()
  • .destroy()

Authentication

To specify an authentication method and related permissions, we've assigned tuples with provided classes to the views authentication_classes and permission_classes attributes.

In this case, to access the UserViewSet (User management API endpoints), the user needs to be either logged in (SessionAuthentication), provide the credentials in the request headers (BasicAuthentication), or provide a per-user token (TokenAuthentication). More on token-based authentication later.

On the other hand, the PointViewSet is accessible by anyone, thus it's a public API endpoint.

Clone this wiki locally