Sitemap
Aryan Singh

Aryan Singh

Talking about Job hunting, Interview preparation, AI, and all the things that can help you land global opportunities.

Introduction to Django for backend development

14 min readFeb 28, 2023

--

Django is a high-level web framework for building web applications. It is built on Python and follows the model-view-controller (MVC) architectural pattern. It is known for its robustness, scalability, and ease of use.

Django provides a number of features that make it easy to build web applications quickly and efficiently. These include:

  • Object-relational mapper (ORM): Django’s ORM allows you to interact with your database using Python code, rather than writing raw SQL. This makes it easy to work with different databases and to switch between them if needed.
  • Automatic admin interface: Django provides an in-built admin interface that makes it easy to manage your data.
  • Templating system: Django provides a powerful templating system that allows you to separate the presentation of your data from the logic of your application.
  • URL routing: Django provides a powerful URL routing system that makes it easy to map URLs to views (Business Logic).

Django REST framework (DRF) is a powerful tool for building RESTful APIs on top of Django. It provides a number of features that make it easy to build APIs, including:

  • Serialization: DRF provides a powerful serialization framework that allows you to easily convert between Python objects and JSON.
  • Authentication and permissions: DRF provides a number of built-in authentication and permission classes that make it easy to control access to your API.
  • Pagination: DRF provides built-in support for pagination, making it easy to handle large datasets.
  • Filtering: DRF provides built-in support for filtering, making it easy to retrieve specific subsets of data.

In this tutorial, we will walk through the process of building a simple RESTful API using Django and DRF. Specifically, we will cover the following steps:

  1. Installation of Django and DRF
  2. Creating a new Django project
  3. Creating a new Django app
  4. Defining a model
  5. Serializing the model
  6. Creating views
  7. URL routing
  8. Testing the API

By following this tutorial, you will be able to create a simple RESTful API using Django and DRF, and be familiar with the concepts of Django and how it works

Installation

The first step in building a Django and DRF based API is to install both libraries. You can do this by running the following command in your command prompt or terminal:

# Install Django
pip install django
# Install Django Rest Framework (DRF)
pip install django djangorestframework

The above cmds will install the django libraries, now we need to start a new Django project with the help of django-admin

django-admin is a command-line utility that comes with Django. It allows you to perform various tasks related to your Django projects, such as creating a new project, creating new apps, running management commands, and more.

A Django project is a collection of settings and configurations for a specific web application. It contains one or more apps, each of which can be used to build a specific functionality or feature of the web application. A project can be created using the django-admin startproject command, which creates a new directory with the basic file structure of a Django project.

Creating a new Django Project

Next, you will need to create a new Django app within your project. You can do this by running the following command:

python manage.py startapp appname

This command will create a new directory within your project with the name of your app and the basic file structure of a Django app.

File Structure of Django

The basic file structure of a Django app typically includes the following:

  • models.py: This file defines the data models for the app, including the fields and behavior of the data. It is used to interact with the database using the built-in Django ORM.
  • views.py: This file defines the views for the app, which handle specific requests and return a response. A view is a Python function that defines how to handle a specific URL.
  • urls.py: This file defines the URLs for the app, including the mapping between URLs and views. It is used to control how URLs are handled by the app.
  • forms.py: This file defines the forms for the app, which are used to handle form submissions and validation.
  • admin.py: This file defines the admin interface for the app, which is used to manage the data through the built-in Django admin interface.
  • migrations/: This directory contains the files related to database migrations. It is used to keep track of changes to the models and apply them to the database.
  • templates/: This directory contains the templates for the app, which define the presentation of the data.
  • static/: This directory contains the static files for the app, such as CSS, JavaScript, and images.

It’s worth mentioning that some apps may not require all of these files, for example if you’re building an API you may not need the templates/ and forms.py files. You can also include other files and directories as per your requirement.

The basic file structure of a Django app is essential to understand and use correctly because it gives a clear overview of how the different components of an app fit together and interact with each other.

Here as we are just building up the APIs so the files of our interest are models.py , views.py admin.py , urls.py and the migrations/ directory.

Django App

A Django app is a self-contained module that can be reused in multiple projects. It is designed to contain all the necessary files and logic for a specific functionality or feature of a web application. An app typically includes models, views, and templates, and can also include other files such as forms, serializers, and custom management commands. An app can be created using the python manage.py startapp command.

the basic file structure of a Django app, including models.py, views.py, urls.py, and migrations/ directory.

A Django project, on the other hand, is a collection of settings and configurations for a specific web application. It contains one or more apps, and it can also include other files such as the manage.py file, which is used to manage the project, and the settings.py file, which contains the settings for the project, including the database settings, installed apps, and other configurations. A project can be created using the django-admin startproject command.

In simple words, a Django project is a collection of apps and configurations that make up a web application, while a Django app is a self-contained module that can be reused in multiple projects and contains the code for a specific functionality or feature of the web application.

It’s worth noting that while a project can have multiple apps, an app can only belong to one project. This allows you to create reusable apps that can be easily plugged into different projects, making development faster and more efficient.

Create a new Django app

  1. Next, you will need to create a new Django app within your project. You can do this by running the following command:
python manage.py startapp appname

This command will create a new directory within your project with the name of your app and the basic file structure of a Django app.

  1. Add the app to INSTALLED_APPS list In the settings.py file of your project . This tells Django to include the app in the project.
  • INSTALLED_APPS = [ ... 'appname', ]
  1. Create Models: Create the models for the app in the models.py file, these models will be used to create the database tables.
  2. Create views: Create views for the app in the views.py file, views handle the request and return the response.
  3. Create URL routing: Create URL routing for the app in the urls.py file, define the URLs that the app should handle and map them to the views.

Django Model

In Django, a model is a Python class that defines the fields and behavior of the data you will be storing. It is used to interact with the database using the built-in Object-relational mapper (ORM).

A model defines the structure of the data, including the fields and their types, as well as any constraints or validation rules. It also defines the behavior of the data, such as how it is stored and retrieved from the database, and any relationships it has with other models.

For example, you might have a model called Book that has fields for the title, author, and publication date, and methods for retrieving all books by a specific author or finding the average rating for all books.

Models are defined in the models.py file of an app, and Django automatically creates a database table for each model. The ORM then allows you to interact with the database using Python code, rather than writing raw SQL, which makes it easy to work with different databases and to switch between them if needed.

In summary, a model in Django is a Python class that defines the structure and behavior of the data you will be storing, and it’s used to interact with the database using the built-in Object-relational mapper (ORM), it allows you to interact with the database using Python code, rather than writing raw SQL, making it easy to work with different databases and to switch between them if needed.

Get Aryan Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

Now, We will define model of the API

from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
  • You can define multiple models for your API as per your requirement.
  • The Model class should be inherited from the model.Model class which comes out of the box of the Django Library.

In this example, the Book model has three fields: title, author, and publication_date. The CharField and DateField options are used to define the data type of the fields.

CharField is used for storing character data and takes an optional max_length parameter. DateField is used for storing date data, it doesn't have any specific parameter.

Django provides many other field options such as IntegerField, FloatField, TextField, BooleanField, EmailField, and more.

The models.Model class also provides a number of other options and methods that can be used to define the behavior of the model, such as:

  • objects : The manager for the model, it's an instance of django.db.models.Manager.
  • Meta : A class that allows you to set additional (meta) options on the model.
  • save() : Saves the model instance to the database.
  • delete() : Deletes the model instance from the database.

The save() delete() and objects methods can be used via the Django ORM

In summary, A model in Django is defined as a Python class that inherits from django.db.models.Model. The class defines the fields and behavior of the data you will be storing, where the fields are defined with the available options such as CharField, IntegerField, DateField and more. The class also provides a number of other options and methods that can be used to define the behavior of the model, such as objects, Meta and more.

Database Migration in Django

In Django, database migration refers to the process of creating, modifying, and deleting database tables and fields to match the models defined in your code.

Django uses a built-in database migration system called django.db.migrations which automatically generates the necessary SQL commands to create, modify, and delete database tables and fields based on the models defined in your code.

When you make changes to your models, such as adding, removing, or modifying fields, you need to create a new migration to reflect those changes in the database. You can create a new migration by running the python manage.py makemigrations command, which will generate a new migration file in the migrations directory of your app.

Once the migration file is created, you can apply the migration to the database by running the python manage.py migrate command. This command will execute the SQL commands in the migration file to create, modify, or delete the necessary tables and fields in the database.

It’s worth noting that Django also keeps track of all the migrations that have been applied to the database, this allows you to roll back to a previous state of the database if needed.

In summary, database migration in Django is the process of creating, modifying, and deleting database tables and fields to match the models defined in your code. Django uses a built-in database migration system that automatically generates the necessary SQL commands based on the models defined in your code. You can create a new migration by running the python manage.py makemigrations command and apply the migration to the database by running the python manage.py migrate command.

Now run the below cmds in your terminal to migrate the DB for the Book model we have created above

# Create migration files
python manage.py makemigrations
# Execute SQL quries on DB
python manage.py migrate

Serialization

Serialization in Django Rest Framework (DRF) exists to handle the conversion of complex data types, such as Django models and querysets, into a format that can be easily rendered into JSON, XML or other content types. This is important because when building an API, it’s common to want to return data from your views and API endpoints in a format that can be easily consumed by other applications.

JSON, XML, and other formats are commonly used to represent data in an API because they are lightweight, easy to parse, and widely supported. However, these formats cannot natively handle complex data types such as Django models and querysets. Serialization solves this problem by providing a way to convert these data types into a format that can be easily rendered into JSON, XML, or other formats.

Serialization also provides a way to validate the data that is being sent to the API, this is useful because it ensures that the data is in the correct format and meets certain constraints before it is processed. This can help to prevent errors and improve the overall reliability of the API.

In summary, Serialization in Django Rest Framework (DRF) exists to handle the conversion of complex data types, such as Django models and querysets, into a format that can be easily rendered into JSON, XML or other content types. It also provides a way to validate the data that is being sent to the API, this ensures that the data is in the correct format and meets certain constraints before it is processed, it makes the API more reliable and easy to consume

DRF provides a built-in serializer class that can be used to serialize and deserialize data. The serializer class defines the fields that should be included in the serialized data, as well as any validation rules that should be applied.

To create a serializer in Django Rest Framework (DRF), you would typically follow these steps:

  1. Import the serializer class: In a new file called serializers.py in your app directory, import the serializer class from the rest_framework module.
from rest_framework import serializers
  1. Create a new serializer class: Define a new class that inherits from the serializers.Serializer or serializers.ModelSerializer class.
class BookSerializer(serializers.ModelSerializer):
  1. Define the fields: Use class attributes to define the fields that should be included in the serialized data. You can use the built-in field classes such as CharField, IntegerField, and DateField, or you can create custom fields.
class BookSerializer(serializers.ModelSerializer):
title = serializers.CharField(max_length=100)
author = serializers.CharField(max_length=100)
publication_date = serializers.DateField()

Views

A view in Django and Django Rest Framework (DRF) is a Python function or class that handles a specific request from a client and returns a response. The view is responsible for performing the logic and business logic of the application, such as handling data validation, authentication, and authorization.

In Django, views can be defined as Python functions or as class-based views. To define a view as a Python function, you would typically create a new file called views.py in your app directory and define a function that takes a request object as an input and returns a response.

In DRF, views are defined as class-based views that inherit from APIView class or other classes that inherit from it such as ListAPIView, CreateAPIView etc. These classes provide built-in functionality for handling common tasks such as data validation, authentication, and authorization. Or you can implement function based views. They are easy to start with.

Lets handle CRUD operations on a model using a serializer in Django Rest Framework (DRF). Here’s an example of how you might implement CRUD operations on a Book model using function-based views and the BookSerializer serializer:

from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from .models import Book
from .serializers import BookSerializer
@api_view(['GET', 'POST'])
def book_list(request):
"""
List all books or create a new book
"""
if request.method == 'GET':
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def book_detail(request, pk):
"""
Retrieve, update or delete a book
"""
try:
book = Book.objects.get(pk=pk)
except Book.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = BookSerializer(book)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = BookSerializer(book, data=request.data

The code above defines two function-based views, book_list and book_detail, to handle CRUD operations on a Book model using the BookSerializer serializer.

book_list function handles the GET and POST requests:

  • GET request: The function retrieves all the books from the database using the Book.objects.all() method and serializes the data using the BookSerializer. The many=True argument is used to indicate that the serializer is handling multiple instances of the model. The serialized data is then returned in the response.
  • POST request: The function receives the data from the request using the request.data attribute, and the data is passed to the serializer using the BookSerializer(data=request.data) constructor. The is_valid() method is used to check if the data is valid. If the data is valid, the serializer's save() method is called to save the data to the database and the serialized data is returned in the response. If the data is invalid, the serializer's errors attribute is returned in the response.

book_detail function handles the GET, PUT and DELETE requests:

  • GET request: The function retrieves a single book from the database using the Book.objects.get(pk=pk) method, where pk is the primary key of the book passed as a parameter in the URL. The book data is then serialized using the BookSerializer and the serialized data is returned in the response.
  • PUT request: The function retrieves a single book from the database using the Book.objects.get(pk=pk) method and deserializes the data using the BookSerializer(book, data=request.data) constructor. The is_valid() method is used to check if the data is valid. If the data is valid, the serializer's save() method is called to save the data to the database and the serialized data is returned in the response. If the data is invalid, the serializer's errors attribute is returned in the response.
  • DELETE request: The function retrieves a single book from the database using the Book.objects.get(pk=pk) method, and the book.delete() method is called to delete the book from the database. The response will have a status code of 204 (No Content) if the deletion was successful.

The api_view decorator is used to specify that these views should be handled as API views, and the permission_classes decorator is used to specify that these views should not require any permissions.

In summary, the code defines two function-based views, book_list and book_detail, that handle CRUD operations on a Book model using the BookSerializer serializer. book_list handles GET and POST requests, and book_detail handles GET, PUT, and DELETE requests. The views use the api_view and permission_classes decorators to specify that these views should be handled as API views and do not require any permissions.

URL Routing

In Django, URL routing is the process of mapping a URL pattern to a view function or class-based view. This is done by including a URL pattern in the urls.py file of your app that maps the request URL to the view function.

Here’s an example of how you might map a URL pattern to a view function:

Copy code
from django.urls import path
from . import views
urlpatterns = [
path('books/', views.book_list, name='book_list'),
path('books/<int:pk>/', views.book_detail, name='book_detail'),
]

In this example, we are using the path function from django.urls to map URL patterns to view functions. The first argument of the path function is the URL pattern, and the second argument is the view function. The name argument is used to give the URL pattern a name, which can be used to reverse the URL later.

The **<int:pk>**in the path function is a URL parameter and in this case it represents the primary key of the book.

Once you’ve defined your URL patterns, you need to include them in your project’s urls.py file so that they can be used by the Django URL dispatcher. You can do this by using the include function from django.urls:

from django.urls import path, include
urlpatterns = [
path('api/v1/', include('books.urls')),
]

In summary, URL routing in Django is the process of mapping a URL pattern to a view function or class-based view. This is done by including a URL pattern in the urls.py file of your app that maps the request URL to the view function using the path function.

Now as your developement is complete you can start the Django server my running.

python [manage.py](<http://manage.py>) runserver at the root of your project. After that your API will be assible via

localhost:8080/api/v1/books

Press enter or click to view image in full size
Photo by Stephen Phillips - Hostreviews.co.uk on Unsplash

--

--

Aryan Singh

Written by Aryan Singh

Talking about Job hunting, Interview preparation, AI, and all the things that can help you land global opportunities.