Statistics
64
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-11-27
Support
Share

AuthorDaniel Correa, Greg Lim

In this book, we take you on a fun, hands-on and pragmatic journey to learning Django API React stack development. You'll start building your first Django API React stack app within minutes. Every chapter is written in a bite-sized manner and straight to the point as we don’t want to waste your time (and most certainly ours) on the content you don't need. In the end, you will have the skills to create a Todo app and deploy it to the Internet. In the course of this book, we will cover Chapter 1: Introduction Chapter 2: Installing Python and Django Chapter 3: Understanding the Project Structure Chapter 4: Creating Our Backend Server Chapter 5: Serialization Chapter 6: URLs and Class-based Views Chapter 7: Creating Todos via the ListCreateAPIView Chapter 8: Permissions Chapter 9: Other C.R.U.D. Operations Chapter 10: Completing a Todo Chapter 11: Authentication – Sign Up Chapter 12: Authentication – Log In Tokens Chapter 13: Introduction to React Chapter 14: Create Navigation Header Bar Chapter 15: Defining Our Routes Chapter 16: TodoDataService - Connecting to the Backend Chapter 17: TodoDataService - Login Component Chapter 18: TodosList Component Chapter 19: Adding and Editing Todos Chapter 20: Deleting a Todo Chapter 21: Completing a Todo Chapter 22: Deployment Chapter 23: Hosting and Deploying our React Frontend The goal of this book is to teach you Django API React stack development in a manageable way without overwhelming you. We focus only on the essentials and cover the material in a hands-on practice manner for you to code along. Working Through This Book This book is purposely broken down into short chapters where the development process of each chapter will center on different essential topics. The book takes a practical hands on approach to learning through practice. You learn best when you code along with the examples in the book. Requirements No previous knowledge on Django or React development is required, but you should have basic programming kno

Tags
No tags
ISBN: 8416644020
Publisher: Independent
Publish Year: 2022
Language: 英文
Pages: 138
File Format: PDF
File Size: 3.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Beginning Django API with React Greg Lim - Daniel Correa Copyright © 2022 Greg Lim All rights reserved. COPYRIGHT © 2022 BY GREG LIM ALL RIGHTS RESERVED. NO PART OF THIS BOOK MAY BE REPRODUCED IN ANY FORM OR BY ANY ELECTRONIC OR MECHANICAL MEANS INCLUDING INFORMATION STORAGE AND RETRIEVAL SYSTEMS, WITHOUT PERMISSION IN WRITING FROM THE AUTHOR. THE ONLY EXCEPTION IS BY A REVIEWER, WHO MAY QUOTE SHORT EXCERPTS IN A REVIEW. FIRST EDITION: FEBRUARY 2022 CO-AUTHOR: DANIEL CORREA
Table of Contents Preface Chapter 1: Introduction Chapter 2: Installing Python and Django Chapter 3: Understanding the Project Structure Chapter 4: Creating Our Backend Server Chapter 5: Serialization Chapter 6: URLs and Class-based Views Chapter 7: Creating Todos via the ListCreateAPIView Chapter 8: Permissions Chapter 9: Other C.R.U.D. Operations Chapter 10: Completing a Todo Chapter 11: Authentication – Sign Up Chapter 12: Authentication – Log In Tokens REACT FRONTEND Chapter 13: Introduction to React Chapter 14: Create Navigation Header Bar Chapter 15: Defining Our Routes Chapter 16: TodoDataService - Connecting to the Backend Chapter 17: TodoDataService - Login Component Chapter 18: TodosList Component Chapter 19: Adding and Editing Todos Chapter 20: Deleting a Todo Chapter 21: Completing a Todo Chapter 23: Hosting and Deploying our React Frontend ABOUT THE AUTHOR ABOUT THE CO-AUTHOR
Preface About this book In this book, we take you on a fun, hands-on and pragmatic journey to learning Django API React stack development. You'll start building your first Django API React stack app within minutes. Every chapter is written in a bite-sized manner and straight to the point as we don’t want to waste your time (and most certainly ours) on the content you don't need. In the end, you will have the skills to create a Todo app and deploy it to the Internet. In the course of this book, we will cover: - Chapter 1: Introduction - Chapter 2: Installing Python and Django - Chapter 3: Understanding the Project Structure - Chapter 4: Creating Our Backend Server - Chapter 5: Serialization - Chapter 6: URLs and Class-based Views - Chapter 7: Creating Todos via the ListCreateAPIView - Chapter 8: Permissions - Chapter 9: Other C.R.U.D. Operations - Chapter 10: Completing a Todo - Chapter 11: Authentication – Sign Up - Chapter 12: Authentication – Log In Tokens - Chapter 13: Introduction to React - Chapter 14: Create Navigation Header Bar - Chapter 15: Defining Our Routes - Chapter 16: TodoDataService - Connecting to the Backend - Chapter 17: TodoDataService - Login Component - Chapter 18: TodosList Component - Chapter 19: Adding and Editing Todos - Chapter 20: Deleting a Todo - Chapter 21: Completing a Todo - Chapter 22: Deployment - Chapter 23: Hosting and Deploying our React Frontend The goal of this book is to teach you Django API React stack development in a manageable way without overwhelming you. We focus only on the essentials and cover the material in a hands-on practice manner for you to code along. Working Through This Book This book is purposely broken down into short chapters where the development process of each chapter will center on different essential topics. The book takes a practical hands on approach to learning through practice. You learn best when you code along with the examples in the book. Requirements No previous knowledge on Django or React development is required, but you should have basic programming knowledge. It will be a helpful advantage if you could read through my Beginning Django and React book first which will provide you will better insight and deeper knowledge into the various technologies. But even if you have not done so, you should still be able to follow along. Getting Book Updates and Source Code To receive updated versions of the book and the source code, send a mail to support@i-ducate.com. I try to update my books to use the latest version of software, libraries and will update the codes/content in this book.
Chapter 1: Introduction Welcome to Beginning Django API with React! This book focuses on the key tasks and concepts to get you started to learn and build a RESTful web API with Django and Django REST Framework, one of the most popular and customizable ways to build web APIs. In the second part of the book, we then show how to create a frontend using React to connect to the API. In all, the book is designed for readers who don ’ t need all the details about Django or React at this point in the learning curve but concentrate on what you really need to know. If you are brand new to Django, I recommend first reading my book, Beginning Django (contact support@i- ducate.com) where we learn about the basics of models, URLs, views, authentication, deployment and more. Why create an API? With Django, we can already create a complete web application. So why bother to create an API with Django and then create separate frontends when we can do it all with Django? Now, say your app becomes a hit. Users love your app so much that they want an iOS and Android version of it. So, you have to create the same functionality of your app in two more different languages (Swift and Kotlin for example). You might also hear of new frontend frameworks like React, Angular, Vue to make your app more dynamic and modern. You want to try them out. How can we better achieve both objectives? The answer is to create a REST API. With Django REST Framework, we can create a common API to serve information to different frontends like Vue, React, Android, iOS etc. We need only to create the logic in the API and then have each of the frontends connect to it. This makes it more scalable and reliable since we just have one code base and database to serve the information. Django Rest Framework The Django Rest Framework (DRF) library enables us to easily create Django APIs that return JSON. DRF takes care of the heavy lifting of transforming database models into a RESTful API. For example, it provides CRUD operations, authentication modules, JSON serializers, routing, and many more. It purposefully mimics many of Django ’ s traditional conventions making it much faster to learn. With a minimal amount of code, DRF can transform any existing Django application into a web API. These will be illustrated as we build our sample application throughout this book. The App We Will Be Building We will build a Todos app which lets users log in, create, view, edit and complete todos (fig. 1a, 1b). Figure 1a – Home Page listing todos
Figure 1b – Create Todo Users can see the list of todos in the home page and post/edit/delete their own todos if they are logged in. They can also mark their todos as ‘ complete ’ . They will not be able to view other user ’ s todos. Through this app, we will learn a lot of concepts and solidify our Django API and React knowledge. We will first create the backend of the app using Django and Django Rest Framework (DRF). After that, we will create the frontend with React and connect the frontend to the backend to complete our Django API – React app. In the last chapter, we will deploy our Django backend on PythonAnywhere, and React frontend on Netlify, to run both backend and frontend in the cloud. So, the overall structure of our app will be: - the Django runs the backend server and exposes an API. Hosted on PythonAnywhere. - the React frontend calls the API and renders the user interface on the client ’ s browser. Hosted on Netlify. In the next chapter, let ’ s begin by installing Python and Django on our machine.
Chapter 2: Installing Python and Django Because Django is a Python web framework, we first have to install Python. Installing Python Let ’ s check if we have Python installed and what version it is. If you are using a Mac, open your Terminal. If you are using Windows, open your Command Prompt. For convenience, I will address both the Terminal and Command Prompt as ‘ Terminal ’ throughout the book. We will need to check if we have at least Python 3.8 to use Django 4. To do so, go to your Terminal and run: Execute in Terminal python3 --version (or python on Windows) This shows the version of Python you installed. Make sure that the version is at least 3.8. If it is not so, get the latest version of Python by going to python.org. Go to ‘ Downloads ’ and install the version for your OS. After the installation, run python3 --version again and it should reflect the latest version of Python e.g. Python 3.10.0 (at time of book ’ s writing). Installing Django We will be using pip to install Django. pip is the standard package manager for Python to install and manage packages not part of the standard Python library. First check if you have pip installed by going to the Terminal and running: Execute in Terminal pip3 (or pip on Windows) If you have pip installed, it should display a list of pip commands. To install Django, run the command: Execute in Terminal pip3 install django This will retrieve the latest Django code and install it in your machine. After installation, close and re-open your Terminal. Ensure you have installed Django by running: Execute in Terminal python3 -m django It will show you all the options you can use (fig. 2.1):
Figure 2.1 Along the course of the book, you will progressively be introduced to some of the options. For now, we will use the startproject option to create a new project. In Terminal, navigate to a location on your computer where you want to store your Django project e.g. Desktop. Create a new folder ‘ todoapp ’ with: Execute in Terminal mkdir todoapp ‘ cd ’ to that folder: Execute in Terminal cd todoapp In todoapp, run: Analyze Code python3 -m django startproject <project_name> In our case, we want to name our project ‘ backend ’ . We run: Execute in Terminal python3 -m django startproject backend A ‘ backend ’ folder will be created. We named the Django project backend because it serves as the backend of the Django-React todo app stack. Later on, the React frontend will be contained in a frontend folder. The eventual structure will look something like: todoapp → backend → Django … → frontend → React … In the next chapter, we will look inside the backend folder that Django has created for us and understand it better.
Chapter 3: Understanding the Project Structure Let ’ s look at the project files created for us. Open the project folder backend in a code editor (I will be using the VSCode editor in this book - https://code.visualstudio.com/). manage.py You will see a file manage.py which we should not tinker. manage.py helps us do administrative things. For example: Analyze Code python3 manage.py runserver to start the local web server. We will later illustrate more of its administrative functions e.g. creating a new app – python3 manage.py startapp db.sqlite3 We also have the db.sqlite3 file that contains our database. We touch more on this file in the Models chapter. backend folder You will find another folder of the same name backend. To avoid confusion and distinguish between the two folders, we will keep the inner backend folder as it is and rename the outer folder to todobackend (fig. 3.1). Figure 3.1 In it, you might have a __pycache__ folder that stores compiled bytecode when we generate our project. You can largely ignore this folder. Its purpose is to make your project start a little faster by caching the compiled code so that it can be readily executed. __init__.py specifies what to run when Django launches for the first time. Again, we can ignore this file. asgi.py allows for an optional Asynchronous Server Gateway Interface to run. wsgi.py which stands for Web Server Gateway Interface helps Django serve our web pages. Both files are used when deploying our app. We will revisit them later when we deploy our app. urls.py This is the file which tells Django which pages to render in response to a browser or URL request. For example, when someone enters a url http://localhost:8000/123, the request comes into urls.py and gets routed to a page based on the paths specified there. We will later add paths to this file and better understand how it works. settings.py The settings.py file is an important file controlling our project ’ s settings. It contains several properties: - BASE_DIR determines where on your machine the project is situated at. - SECRET_KEY is used when you have data flowing in and out of your website. Do not ever share this with others. - DEBUG – Our site can run in debug or not. In debug mode, we get detailed information on errors. For e.g. if I run http://localhost:8000/123 in the browser, I will see a 404 page not found with details on the error
(fig. 3.2). Figure 3.2 If DEBUG = False, we will see a generic 404 page without error details. While developing our project, we set DEBUG = True to help us with debugging. When deploying our app to production, we should set DEBUG to False. - INSTALLED_APPS allow us to bring in different pieces of code into our project. We will see this in action later. - MIDDLEWARE are built-in Django functions to help in our project. - ROOT_URLCONF specify where our URLs are. - TEMPLATES help us return HTML code. - AUTH_PASSWORD_VALIDATORS allow us to specify validations we want on passwords. E.g. a minimum length. There are some other properties in settings.py like LANGUAGE_CODE and TIME_ZONE but we have focused on the more important ones. We will later revisit this file and see how relevant it is in developing our site. Let ’ s next create our backend server!
Chapter 4: Creating Our Backend Server Now, it ’ s time to create the backend server! A single Django project can contain one or more apps that work together to power an API. Django uses the concept of projects and apps to keep code clean and readable. In the todobackend folder, create a new app ‘todo’ with the command: Execute in Terminal python3 manage.py startapp todo A new folder todo will be added to the project. As we progress along the book, we will explain the files inside the folder. Though our new app exists in our Django project, Django doesn ’ t ‘ know ’ it till we explicitly add it. To do so, we specify it in settings.py. So go to … /backend/settings.py, under INSTALLED_APPS, add the app name (shown in bold): Modify Bold Code … INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo', ] … Models Working with databases in Django involves working with models. We create a database model (e.g. todo, book, blog post, movie) and Django turns these models into a database table for us. In … /backend/todo, you have the file models.py where we create our models. Let’s create our todo model by filling in the following: … /todo/models.py: Replace Entire Code from django.db import models from django.contrib.auth.models import User class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) #set to current time created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) #user who posted this user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Code Explanation Analyze Code from django.db import models Django imports a module models to help us build database models which ‘ model ’ the characteristics of the data in the database. In our case, we created a todo model to store the title, memo, time of creation, time of completion and user who created the todo. Analyze Code class Todo(models.Model) class Todo inherits from the Model class. The Model class allows us to interact with the database, create a table, retrieve and make changes to data in the database.
Note that we use Django ’ s built in User model (imported at the second line from the top) as the creator of the todo. Analyze Code title = models.CharField(max_length=100) memo = models.TextField(blank=True) #set to current time created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) #user who posted this user = models.ForeignKey(User, on_delete=models.CASCADE) We then have the properties of the model. Notice that the properties have types like CharField, TextField, DateTimeField. Django provides many other model fields to support common types like dates, integers, emails, etc. To have a complete documentation of the kinds of types and how to use them, refer to the Model field reference in the Django documentation (https://docs.djangoproject.com/en/4.0/ref/models/fields/). If any of the above feels new to you, it will be good to pause here and review Beginning Django (contact support@i-ducate.com) for more explanation of traditional Django. Analyze Code def __str__(self): return self.title We also include a __str__ method so that the title of a todo will display in the admin later on. With this model, we can create a Todo table in our database. Migrations Whenever we create a new model or make changes to it in models.py, we need to update Django in a two-step process. First, in /todoapp/todobackend/, we create a migration file with the makemigrations command: Execute in Terminal python3 manage.py makemigrations This generates the SQL commands (migrations) for preinstalled apps in our INSTALLED_APPS setting. The SQL commands are not yet executed but are just a record of all changes to our models. The migrations are stored in an auto-generated folder migrations (fig. 1). Figure 1 Second, we build the actual database with the following: Execute in Terminal python3 manage.py migrate The migrate command creates an initial database based on Django ’ s default settings and executes the SQL commands in the migrations file. Notice there is a db.sqlite3 file in the project folder. The file represents our SQLite database. It is created the first time we run migrate. migrate syncs the database with the current state of any database models in the project and listed in INSTALLED_APPS. It is thus essential that after we update a model, we need to run migrate. In summary, each time you make changes to a model file, you have to run: Analyze Code python3 manage.py makemigrations python3 manage.py migrate * Contact support@i-ducate.com for the source code of the completed project
Adding todos to the database We will add some todo data via the build-in admin site. Django has a powerful built-in admin interface which provides a visual way of managing all aspects of a Django project, e.g. users, making changes to model data. To access the Admin site, start your local Django server by going to …/todobackend/ and running in the Terminal: Execute in Terminal python3 manage.py runserver In the browser, go to http://localhost:8000/admin/ where you will see a log in form (fig. 2). Figure 2 With what username and password do we log in to Admin? We will have to first create a superuser in the Terminal. Open a new Terminal, and in … /todobackend/, run: Execute in Terminal python3 manage.py createsuperuser You will then be asked to specify a username, email and password. Note that anyone can access the admin path on your site, so make sure your password is something secure. We next have to add the Todo model to admin by going to …/todo/admin.py, and register our Todo model with: Modify Bold Code from django.contrib import admin from .models import Todo # Register your models here. admin.site.register(Todo) When you save your file and log back into http://localhost:8000/admin/. The Todo model will now show up (fig. 3). Figure 3 Try adding a todo object by clicking on ‘ +Add ’ . You will be brought to a Add Todo Form (fig. 4).
Figure 4 Try adding a todo and hit ‘ Save ’ . Note that you have to specify a user (fig. 5). Figure 5 Your todo object will be saved to the database and reflected in the admin (fig. 6). Figure 6 Now that we know how to add todo objects to our database via admin, let ’ s carry on with building our API.
Chapter 5: Serialization Django REST Framework We will use the Django REST Framework to help build our API. You can build APIs on your own in Django but it will take a lot of work. The Django Rest Framework helps us quickly build reliable and secure APIs. There are a ton of documentation in the DRF site ((https://www.django-rest-framework.org/) but this book will show you the best parts of the framework. Installation Install DRF using pip: Execute in Terminal pip3 install djangorestframework Next, add 'rest_framework' to your INSTALLED_APPS setting in ../backend/settings.py: Modify Bold Code ... INSTALLED_APPS = [ ... 'todo', 'rest_framework', ] ... Adding the API app We create a dedicated api app to contain API specific files. So in the Terminal, under ../todobackend/, run the command: Execute in Terminal python manage.py startapp api We'll need to add our new api app to INSTALLED_APPS. In todobackend/backend/settings.py, add: Modify Bold Code ... INSTALLED_APPS = [ ... 'todo', 'rest_framework', 'api', ] ... To get started on our API, we declare Serializers which translate data from the Todo Model instances into JSON objects that is easy to consume over the Internet. The JSON objects are outputted at API endpoint urls. Django REST framework shops with a powerful built-in serializer class that we can quickly extend with some code. In the api folder, create the file serializers.py with the following code: Add Code from rest_framework import serializers from todo.models import Todo class TodoSerializer(serializers.ModelSerializer): created = serializers.ReadOnlyField() completed = serializers.ReadOnlyField() class Meta: model = Todo fields = ['id','title','memo','created','completed'] Code Explanation Analyze Code class TodoSerializer(serializers.ModelSerializer): We extend DRF’s ModelSerializer into a TodoSerializer class. ModelSerializer provides an API to create serializers from your models.
Analyze Code class Meta: model = Todo fields = ['id','title','memo','created','completed'] Under class Meta, we specify our database model Todo and the fields we want to expose i.e. ['id','title','memo','created','completed']. Django REST Framework then magically transforms our model data into JSON, exposing these fields from our Todo model. Fields not specified here will not be exposed in the API. Remember that ‘id’ is created automatically by Django so we didn’t have to define it in Todo model. But we will use it in our API. Often, an underlying database model will have more fields than what needs to be exposed. DRF’s serializer class’s ability to include/exclude fields in our API is a great feature and makes it straightforward to control this. Analyze Code # auto populated by app. User can’t manipulate created = serializers.ReadOnlyField() completed = serializers.ReadOnlyField() Additionally, we specify that created and completed fields are read only. I.e., they cannot be edited by a user (because they ought to be auto-populated when a todo is created and when it is marked as complete). Now that we have our first serializer, let ’ s see how to setup URLs for our API endpoints in the next chapter.
Chapter 6: URLs and Class-based Views For the API app to have its own urls.py to contain the paths for the API end points, we add the below to todobackend/backend/urls.py: Modify Bold Code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), ] This will forward all API related paths e.g. localhost:8000/api/* to the API app. Creating our first route In /todobackend/api/, create a new file urls.py which will contain the routes of the different endpoints. Add in the below code: Add Code from django.urls import path from . import views urlpatterns = [ path('todos/', views.TodoList.as_view()), ] We have one route ‘/todos’ as a demonstration. What we want to achieve is that when a request is made to localhost:8000/api/todos, you should get a JSON response with the list of todo instances. But how do we achieve this? The answer is in views.TodoList.as_view(). In traditional full stack Django projects, views are used to customize what data to send to the HTML templates. In our API project, we use class-based generic views (from DRF) to similarly send customized serialized data but this time, to the API endpoints instead of to templates. views.TodoList is an instance of a class-based generic view. Django’s generic views help us quickly write views (without having to write too much repetitive code) to do common tasks like: - Display a list of objects, e.g. list of todos. - Display detail pages for a single object. E.g. detail page of a todo. - Allow users to create, update, and delete objects – with or without authorization. Things will be clearer as we implement our TodoList generic view. Thus, in todobackend/api/views.py, replace the code with the following: Replace Entire Code from rest_framework import generics from .serializers import TodoSerializer from todo.models import Todo class TodoList(generics.ListAPIView): # ListAPIView requires two mandatory attributes, serializer_class and # queryset. # We specify TodoSerializer which we have earlier implemented serializer_class = TodoSerializer def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user).order_by('-created') Code Explanation Analyze Code from rest_framework import generics We import DRF ’ s generics class of views. Analyze Code class TodoList(generics.ListAPIView):
We then create TodoList that uses generics.ListAPIView. ListAPIView is a built-in generic class which creates a read-only endpoint for model instances. ListAPIView requires two mandatory attributes which are serializer_class and queryset. When we specify TodoSerializer as the serializer class, we create a read-only endpoint for todo instances. There are many other generic views available and we explore them later. Analyze Code def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user).order_by('-created') get_queryset returns the queryset of todo objects for the view. In our case, we specify the query set as all todos which match the user. Additionally, we order the todos by the created date i.e. we show the latest todo first. You can customize get_queryset to return the set of todos that you want. Running our App In Terminal, cd to the todobackend directory and run python3 manage.py runserver to test run your app. Go to localhost:8000/api/todos and you can see the data in JSON format visualized (fig. 1)! Note you must be logged in the admin section with your admin user, before accessing the previous route. Figure 1 DRF provides this powerful visualization by default. There are lots of other functionality in this page that we will explore throughout the book. As you add more todos via the Admin, they will show up in the API endpoint as you reload the page. And you just created your first API endpoint with Django Rest Framework! See how DRF generic views help us to quickly implement these endpoints with little code? But what about endpoints that allow us to create, update or delete? We will explore them in the following chapters.
Chapter 7: Creating Todos via the ListCreateAPIView The ListAPIView we used in the previous chapter provides us with a read-only endpoint of todo model instances. To have a read-write endpoint, we use ListCreateAPIView. It is similar to ListAPIView but allows for creation as well. In todobackend/api/views.py, add the following in bold: Modify Bold Code ... class TodoListCreate(generics.ListCreateAPIView): # ListAPIView requires two mandatory attributes, serializer_class and # queryset. # We specify TodoSerializer which we have earlier implemented serializer_class = TodoSerializer def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user).order_by('-created') All we have to do is just change ListAPIView to ListCreateAPIView, and automatically, the write operation is allowed for the given API end point! This is the advantage of a fully featured framework like Django REST Framework. The functionality is available and just works. Developers don’t have to write much code and implement it themselves. Note that we have to update our view name in todobackend/api/urls.py: Modify Bold Code ... urlpatterns = [ path('todos/', views.TodoListCreate.as_view()), ] To test our API, go to localhost:8000/api/todos on the browser, and you will now see a form/raw data (JSON) below (fig. 1) that you can enter to create a new todo. Figure 1 However, when you attempt to add a todo via the form, you get an error like (fig. 2): Figure 2 This is because we have not specified a user who created this todo. To do so, we have to customize the creation process using perform_create. perform_create What is missing currently is when we create a todo, we should automatically assign the user who created it. So how can we customize the creation process in our API?
In todobackend/api/views.py, add the below perform_create method: Modify Bold Code ... class TodoListCreate(generics.ListCreateAPIView): # ListAPIView requires two mandatory attributes, serializer_class and # queryset. # We specify TodoSerializer which we have earlier implemented serializer_class = TodoSerializer def get_queryset(self): user = self.request.user return Todo.objects.filter(user=user).order_by('-created') def perform_create(self, serializer): #serializer holds a django model serializer.save(user=self.request.user) perform_create acts as a hook which is called before the instance is created in the database. Thus, we can specify that we set the user of the todo as the request’s user before creation in the database. These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. In our case, we set the todo’s user based on the request user. See how Django allows many auto-generated features yet also allow these customizations? Running your App When you attempt to add a todo via the form now, your todo should be successfully added. If you reload the endpoint at localhost:8000/api/todos/, the new todo should be in the JSON results.
The above is a preview of the first 20 pages. Register to read the complete e-book.