Skip to content

Commit

Permalink
Added details on APIViews
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Mar 13, 2018
1 parent a4b94c0 commit 4451002
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
43 changes: 40 additions & 3 deletions docs/views-and-generic-views.rst
Original file line number Diff line number Diff line change
@@ -1,15 +1,52 @@
Views and Generic Views
============================

In this chapter, we will create views using :code:`APIVIew`, and :code:`generics.ListCreateAPIView` and family.

Creating Views with :code:`APIView`
-----------------------------------------


To start with, we will use the :code:`APIView` to build the polls list and poll detail API we built in the chapter, doc:apis-without-drf:.

Add this to a new file :code:`polls/apiviews.py`

.. code-block:: python
class PollList(APIView):
def get(self, request):
polls = Poll.objects.all()[:20]
data = PollSerializer(polls, many=True).data
return Response(data)
class PollDetail(APIView):
def get(self, request, pk):
poll = get_object_or_404(Poll, pk=pk)
data = PollSerializer(poll).data
return Response(data)
And change your :code:`urls.py` to

.. code-block:: python
from django.urls import path
from .apiviews import PollList, PollDetail
urlpatterns = [
path("polls/", PollList.as_view(), name="polls_list"),
path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail")
]
Using DRF generic views to simplify code
-----------------------------------------

Creating Views
----------------

Let us use generic views of Django Rest Framework for creating our views which will help us in code reusablity. The generic views alos aid us in building the API quickly and in mapping the database models.
Let us use generic views of Django Rest Framework for creating our views which will help us in code reusablity. The generic views also aid us in building the API quickly and in mapping the database models.

.. code-block:: python
Expand Down
2 changes: 1 addition & 1 deletion pollsapi/polls/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.urls import path

from .views import polls_list, polls_detail
from .apiviews import PollList, PollDetail

urlpatterns = [
path("polls/", PollList.as_view(), name="polls_list"),
path("polls/<int:pk>/", PollDetail.as_view(), name="polls_detail")
Expand Down

0 comments on commit 4451002

Please sign in to comment.