Build REST API in Django Using Rest Framework [Function based views]

1 . Introduction

In this post, we are going to learn about function based views in Django. Django has two types of views; function-based views (FBVs), and class-based views (CBVs). Django originally started out with only FBVs, but then added CBVs as a way to templatize functionality so that you didn’t have to write boilerplate (i.e. the same code) code over and over again.

2. Setup

Let's create a project first and setup URLs (skip this section if you are already aware of this setup).

#Create a fresh virtual environment
mkvirtualenv env (On creating, env will be activated automatically. Activate it if you navigate to a new tab.)

#Install Django 
pip install Django

#Go to your favourite directory and create a new project startproject StudentService

#Important step. Perform all the operations in this directory. When I say 'project_template' directory in future, it points to the directory present inside this, i.e,. project_directory/project_directory.
cd StudentService
Lets create a sample app 'students'.

python startapp students

3. Setting Up Project
Add 'students' + rest_framework to installed apps in your files


Modify your Database settings as well. We are going to work with MYSQL Database

Add this to your file

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'studentdb',
        'USER': 'root',
        'PASSWORD': ''

4. Working with models

Let's build the model for our API. In this example, we are going to see how to store students scores for examinations.

We are going to capture ID, NAME & score details of each individual student. 

Add the below code to the inside the student's folder.

from django.db import models

# Create your models here.

class Students(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length = 20)
    score = models.DecimalField(max_digits=10,decimal_places=3)

    def __str__(self):

5. Adding Serializers

Now its time to create a Serializers for API. 

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

First, create a file called and add the below code.

from rest_framework import serializers
from students.models import Students

class StudentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = ["id","name","score"]

in the fields, sections above you can use __all__ to add all the columns for serializations. If you want to capture individual ones you can pass a list of column names.

6. Updating the

Finally, let's create

First we need to be able to fetch all the results by performing a GET and also should be able to add a new student record.

The below code helps you fetch all records on GET and add new student details. The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: 

def students_list(request):
    if request.method == 'GET':
        students = Students.objects.all()
        serializers = StudentSerializers(students,many=True)
        return Response(

    elif(request.method == 'POST'):
        serializers = StudentSerializers(
        if serializers.is_valid():
            return Response(,status=status.HTTP_201_CREATED)
        return Response(serializers.errors,status=status.HTTP_400_BAD_REQUEST)
In the next scenario we are going to see how to work with individual student records using GET,PUT,DELETE

The PK here is the primary key column in your database which is ID in our case. 

def students_details(request,pk):
        student = Students.objects.get(pk=pk)
    except Students.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializers = StudentSerializers(Students)
        return Response(

    elif request.method == 'PUT':
        serializers = StudentSerializers(Students,
        if serializers.is_valid():
            return Response(
        return Response(serializers.errors,status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        return Response(status=status.HTTP_204_NO_CONTENT)
Make sure to import all the necessary modules 

from students.models import Students
from students.serializers import StudentSerializers
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

7. Finally
Last we will add the URLs to make sure we are able to hit it via the endpoints

Add/update the URL patterns in in StudentService

urlpatterns = [
    path('students/', views.students_list),
    path('students/', views.students_details),


This function based views is very easy to implement and it’s very useful but the main disadvantage is that on a large Django project, usually a lot of similar functions in the views. If all objects of a Django project usually have CRUD operations so this code is repeated again and again unnecessarily and this was one of the reasons that the class-based views and generic views were created for solving that problem.


We saw how to use the function based views in this post while there are other types of views as well which we will cover in upcoming posts. if you want to know if function based views are best among all then it all depends on the context and the needs. As I mentioned in the beginning of this post, class-based views does not replace function-based views. There are cases where function-based views are better. In other cases, class-based views are better.

How to build a User Registration(Login/Signup/Logout) System in Django

1. Introduction

In this post, we are going to see how to build a User registration system in Django using the auth module in Django. The example will cover steps to build your registration system where users can register(signup)/login using the credentials and logout of the system.

Let's get Started! 

2. Starting a new Project 

If you are new to Django, please make sure to check out the steps to create a virtual envt in python before creating a Django project. If you already have one you can continue to follow along with me.

Step #1 : Create a Django project

We are not going to use any database-model for this tutorial, we will cover soon in some other post. Let's create a new Django project by running the below command inside your virtual env.

 django-admin startproject mysite

Step #2: Create a Django app

In this tutorial, we’ll create our accounts app in the same directory as your file so that it can be imported as its own top-level module, rather than a submodule of mysite.

To create your app, make sure you’re in the same directory as and type this command:

python startapp accounts

Once done you should be able to see a below folder structure with the below files.

Step #3: Update your

Make sure to update your with a new app so that it can be picked up while running the server.



3. Building your Base template for homepage/signup page/login page/login

First, we are going to build a base template for our homepage using Bootstrap. Navigate to mysite ((app) inside the main mysite project). create a template folder and add a file called base.html

You can paste the below code inside base.html .This will be a basic template which we are going to use in our project.

<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">


  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">



    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="">NintyZero</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
  <div class="container">
      {% block content %}
      {% endblock %}

  <footer class="text-muted">
    <div class="container text-center">
      <p>This is a footer {% now "Y" %}</p>

  <!-- Bootstrap core JavaScript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


4.Updating the URL for navigation 

To update the URL pattern (for ex we want to show login page once user reaches account/login or account/signup. we can do that by adding the URL pattern in file(if not found create one) inside your mysite folder and add the below code.

from django.contrib import admin
from django.urls import path,include
from products import views

urlpatterns = [
    path('accounts/',include ('accounts.urls')),

5.Adding view for Login/Signup/Logout

Create a template/account folder inside account app and add two Html files named login.html and signup.html

Use the below code to create a Signup Page

{% extends 'base.html' %}

{% block content %}

{% if error %}
{{ error }}

{% endif %}


<form method = "POST" action="{% url 'signup' %}">
    {% csrf_token %}
    <input type="text" name="username" />
    <input type="password" name="password1" />
    confirm Password:
    <input type="password" name="password2" />
    <input class ="btn btn-primary" type="submit" value= "signup" />


{% endblock %}

{% extends 'base.html' %}

{% block content %}

{% if error %}
{{ error }}

{% endif %}


<form method = "POST" action="{% url 'login' %}">
    {% csrf_token %}
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input class ="btn btn-primary" type="submit" value= "Login" />


{% endblock %}

6. Adding the logic for login and signup

Open the (create one if now found) inside accounts app folder and add the below code to it.

from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import auth

def signup(request):
    if request.method == "POST":
        if request.POST['password1'] == request.POST['password2']:
                User.objects.get(username = request.POST['username'])
                return render (request,'accounts/signup.html', {'error':'Username is already taken!'})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['username'],password=request.POST['password1'])
                return redirect('home')
            return render (request,'accounts/signup.html', {'error':'Password does not match!'})
        return render(request,'accounts/signup.html')

def login(request):
    if request.method == 'POST':
        user = auth.authenticate(username=request.POST['username'],password = request.POST['password'])
        if user is not None:
            return redirect('home')
            return render (request,'accounts/login.html', {'error':'Username or password is incorrect!'})
        return render(request,'accounts/login.html')

def logout(request):
    if request.method == 'POST':
    return redirect('home')


In this post, we learned how to build a user login and signup systems. we also saw how to build views and use it to register and log in.

Getting Started with Django Quickly [Step by Step tutorial]

1. Introduction:

In this post, we are going to see an overview of Django (as a tutorial) and setting up the environment to get started with building WebApps or Rest APIs.

Before we start setting up the environment we can have a look into the features Django brings to help with development.

YouTube-Style Face Detect - Crop and Blur using python and OpenCV

This post will focus on the core concepts in image processing. These areas will act as the building blocks for more intricate image manipulations in a later post. Becoming familiar with these characteristics of using Python and OpenCV, we will then be able to jump around to the different concepts more easily. 

Face processing is a hot topic in artificial intelligence because a lot of information can be automatically extracted from faces using computer vision algorithms. 

The face plays an important role in visual communication because a great deal of non-verbal information, such as identity, intent, and emotion, can be extracted from human faces.

Face processing is a really interesting topic for computer vision learners because it touches on different areas of expertise, such as object detection, image processing, and landmark detection or object tracking.

A Simple Explanation of Regularization in Machine Learning

In this post, we are going to look into regularization and also implement it from scratch in python (Part02). We will see with example and nice visuals to understand it in a much better way. We already know about the Linear regression where this is used.

In-depth Explained Simple Linear Regression from Scratch - Part 1

In my opinion, most Machine Learning tutorials aren’t beginner-friendly enough. It very math-heavy or it doesn't help you with the algorithms behind it.
In this post, we are going to do the simple Linear Regression from scratch. We will see the mathematical intuition behind it and we write the code from scratch + test it and I'm super excited to get started!!

Overview Guide To Tensorflow 2.x with Examples

The most concise and complete explanation of what TensorFlow is can be found at ( and it highlights every important part of the library.

TensorFlow is an open-source software library for high-performance numerical computation.

Its flexible architecture allows easy deployment of computation across a range of platforms (CPUs, GPUs, and TPUs), from desktops to clusters of servers, to mobile and edge devices.

Originally developed by researchers and engineers from the Google Brain team within Google's AI organization, it comes with strong support for machine learning and deep learning,and therefore the flexible numerical computation core is employed across many other scientific domains.

In this blog post, we are going to see the basics for TensorFlow 2.x. This can be used as getting started guide to learn and understand it.

I'm not going to cover the installation/Setup of the Jupyter part as this can be found online easily.

Create a CRUD Restful Service API using Flask + Mysql [in 7 minutes!]

In this article, we will learn how to build Simple Restful API with flask and Mysql that have capabilities to create, read, update, and delete data from the database.

Flask being a microframework provides the flexibility of the data source for applications and also provides library support for interacting with different kinds of data sources. There are libraries to connect to SQL- and NoSQL-based databases in Flask.

Error and Exception Handling using Try/catch in powershell

One of the most important components for creating PowerShell scripts is error and exception handling.

I've personally made mistakes while writing scripts without proper exceptions and trying to figure out why it got terminated.😵 

Error and exception handling is often a forgotten component of scripting because it's common to feel that the code should always execute linearly and in an implicit fashion.

This is due to the common practice of taking the small scripts and using them as starting points for more complex scripts. 

The more complex you build your scripts, the higher the probability of failure 🠝 and unexpected results.

In this post, you will learn the following:
  • Types of error
  • Different ways to handle Exceptions
  • Error and exception handling with parameters
    • Different Actions
  • Error and exception handling with Try/Catch

PowerShell has two different types of errors which are terminating and non-terminating.

Terminating errors will stop the script from executing further commands. 

The non-terminating errors will call the write-error cmdlet, print an error to the screen, and continue.

Error and Exception Handling 

PowerShell offers several different options to achieve error and exception handling.

The most popular method used to catch non-terminating errors is bypassing the error and exception handling parameters while executing PowerShell cmdlets. 

You can then call the error variable and execute other actions based on the contents of the $error variable.

The PowerShell parameters that handle error and exceptions are -WarningAction and ErrorAction

When an issue occurs with your script, the PowerShell CLR will reference the -ErrorAction and -WarningAction arguments to determine what the next step for the script is.

There are five actions that are supported within PowerShell. 

  • The SilentlyContinue action will suppress the error and warning information, populate the error variables, and continue.
  • The Ignore action will suppress the warning and error message and not populate any specified variables.
  • The Continue action will write to the screen the warning and error information and attempt to continue with the script.
  • The Stop action will write the warning and error information stop the execution of the script.
  •  The Inquire action will prompt the end-user if they want to HaltSuspendAccept the Error, or Accept All Errors.

By default, PowerShell is set to Continue, however, you can set the $errorActionPreference and $warningActionPreference (Global variables) to different values for different default actions.

We will see one example of cmdlet error handling.

Function TestExample($tesparam) { 
Get-service $tesparam –ErrorAction SilentlyContinue –ErrorVariable err

    If ($err) {
      Write-host "Error! Error Details: $err"
    Write-host "Successfully Retrieved Service Information for $svcName. "
TestExample "Windows Update"
Write-host "" 
TestExample "Does Not Exist"

Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  wuauserv           Windows Update                        
Successfully Retrieved Service Information for . 

Error! Error Details: Cannot find any service with service name 'Does Not Exist'.

If the $err variable has data in it or is implied true, the script will write to the console Error! Error Details: $err followed by return, which will exit out of the function. If the $err variable doesn't have any error details, it will proceed to write to the console.

Handling error with try/Catch/Finally

One of the more popular error and exception handling techniques is leveraging Try/Catch methodology.

The Try/Catch block is used for handling terminating errors and has a very simple structure. You first use the Try { } section of code and then use Catch { } to catch any errors and perform actions based on the errors.

    $items = Get-Item -Path C:\Does\Not\Exist, C:\Windows, $env:APPDATA -ErrorAction Stop
catch [System.Management.Automation.ItemNotFoundException]
    # Specific catch block for the exception type
    # PSItem contains the error record, and TargetObject may contain the actual object raising the error
    Write-Host ('Could not find folder {0}' -f $PSItem.TargetObject)
    # Regardless of whether an error occurred or not, the optional
    # finally block is always executed.
    Write-Host 'Always executed'

You can find out which type of exception occurred by examining its type, using $Error[0].Exception.GetType().FullName.

One of the best practice techniques for error and exception handling is to combine the use of the Try/Catch block and cmdlet parameters. This is due to PowerShell being able to gracefully handle terminating and non-terminating error scenarios. 

For instance, if you execute a line of code that throws a warning message but doesn't generate a terminating error, you can catch the warning and perform actions based on that warning.

Try {
    Get-process "Doesn't Exist" –ErrorAction SilentlyContinue     –ErrorVariable err
Catch {
  Write-host "Try/Catch Exception Details: $_"
if ($err) {
  Write-host "Cmdlet Error Handling Error Details: $err"

Cmdlet Error Handling Error Details: Cannot find a process with the name "Doesn't Exist". Verify the process name and call the cmdlet again. 

When you execute the script, you see that the Catch method doesn't catch the error message from the get-service  the cmdlet. This is due to the error being a non-terminating error, and so it doesn't invoke the block

When you run the script, however, the cmdlet properly handles the error and places the error details in the $err variable. 

Quick Summary: 
  • There are two types of errors in PowerShell: terminating and nonterminating.
  • Error records are written directly to the default output.
  • Error records are rich objects.
  • The $error variable stores the last 256 errors (by default).
  • You can specify a specific variable for errors by using the -ErrorVariable parameter.
  • $? stores a Boolean value indicating the execution status of the last command.
  • $ErrorActionPreference and the -ErrorAction parameter can be used to control the action taken if an error occurs.
  • Terminating errors and exceptions can be managed by the trap statement or the try/catch/finally statements (preferred).
Happy Coding!