❌

Reading view

There are new articles available, click to refresh the page.

Getting Started with Django: Creating Your First Project and Application

Django is a powerful and versatile web framework that helps you build web applications efficiently. Here’s how you can set up a Django project and create an application within it.

Step 1: Install Django

First, you’ll need to install Django on your machine. Open your terminal or command prompt and run:

pip install django

Step 2: Check Django Version

To confirm Django is installed, you can check the version by running:

python3 -m django --version

Step 3: Set Up Project Directory

Organize your workspace by creating a folder where your Django project will reside. In the terminal, run:

mkdir django_project
cd django_project

Step 4: Create a Django Project

Now, create a Django project within this folder. Use the following command:

django-admin startproject mysite

This will create a new Django project named mysite.

Project Structure Overview

Once the project is created, you’ll notice a few files and folders within the mysite directory. Here’s a quick overview:

  • manage.py: A command-line utility that lets you interact with this Django project in various ways (starting the server, creating applications, running migrations, etc.).
  • __init__.py: An empty file that tells Python to treat the directory as a Python package.

Step 5: Run the Development Server

Now that the project is set up, you can test it by running Django’s development server:

python3 manage.py runserver

Visit http://127.0.0.1:8000/ in your browser, and you should see the Django welcome page, confirming your project is working.

Step 6: Create an Application

In Django, projects can contain multiple applications, each serving a specific function. To create an application, use the command:

python3 manage.py startapp firstapplication

This will create a folder named firstapplication inside your project directory, which will contain files essential for defining the app’s models, views, templates, and more.

With this setup, you’re ready to start building features in Django by defining models, views, templates, and URLs. This foundation will help you build scalable and structured web applications efficiently.


TASKS:

1. Create a Django Application to display Hello World Message as response.

2. Create One Django Application with multiple views.

3. Create a Django Application to display Current Date and Time.

Open settings.py inside the project folder and add a application name(firstapplication) to INSTALLED APPS List[]

Next open the views.py inside the application folder import httpresponse and create a function.

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def display(request):
    views_content='<h2>HELLO WORLD!<H2>'
    return HttpResponse(views_content)

def display1(request):
    views_content='<h2>WELCOME TO DJANGO<H2>'
    return HttpResponse(views_content)

def display2(request):
    views_content='<h2>WELCOME TO MY APPLICATION<H2>'
    return HttpResponse(views_content)

import datetime

# Create your views here.

def time_info_view(request):
    time = datetime.datetime.now()
    output = '<h1> Currently the time is ' + str(time) + '</h1>'
    return HttpResponse(output)

next open the urls.py inside the project folder

from firstapplication(application) import views

create a urls of the page in urlpatterns list[]

from django.contrib import admin
from django.urls import path
from firstapplication import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('welcome/',views.display),
    path('second/',views.display1),
    path('third/',views.display2),
    path('datetime/',views.time_info_view)
]

Now open the local host 127.0.0.1:8000 you will see the below page

it contains 5 pages admin(default),welcome,second,third,datetime these are we created ones.

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/welcome/ you will see below page

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/datetime/ you will see below page

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/second/ you will see below page

If you change the path 127.0.0.1:8000 to 127.0.0.1:8000/third/ you will see below page

These are the essential steps for creating a Django project as a beginner, helping you understand the basic setup and flow of a Django application.

Binary Insertion Sort

Introduction

Binary insertion sort is a sorting algorithm similar to insertion sort, but instead of using linear search to find the position where the element should be inserted, we use binary search. Thus, we reduce the number of comparisons for inserting one element from O(N) (Time complexity in Insertion Sort) to O(log N).

Best of two worlds

Binary insertion sort is a combination of insertion sort and binary search.

Insertion sort is sorting technique that works by finding the correct position of the element in the array and then inserting it into its correct position. Binary search is searching technique that works by finding the middle of the array for finding the element.

As the complexity of binary search is of logarithmic order, the searching algorithm’s time complexity will also decrease to of logarithmic order. Implementation of binary Insertion sort. this program is a simple Insertion sort program but instead of the standard searching technique binary search is used.

How Binary Insertion Sort works ?

Process flow:

In binary insertion sort, we divide the array into two subarrays β€” sorted and unsorted. The first element of the array is in the sorted subarray, and the rest of the elements are in the unsorted one.

We then iterate from the second element to the last element. For the i-th iteration, we make the current element our β€œkey.” This key is the element that we have to add to our existing sorted subarray.

Example

Consider the array 29, 10, 14, 37, 14,

First Pass

Key = 1

Since we consider the first element is in the sorted array, we will be starting from the second element. Then we apply the binary search on the sorted array.

In this scenario, we can see that the middle element in sorted array (29) is greater than the key element 10 (key = 1).

Now we need to place the key element before the middle element (i.e.) to the position of 0. Then we can shift the remaining elements by 1 position.

Increment the value of key.

Second Pass

Key = 2

Now the key element is 14. We will apply binary search in the sorted array to find the position of the key element.

In this scenario, by applying binary search, we can see key element to be placed at index 1 (between 10 and 29). Then we can shift the remaining elements by 1 position.

Third Pass

Key = 3

Now the key element is 37. We will apply binary search in the sorted array to find the position of the key element.

In this scenario, by applying binary search, we can see key element is placed in its correct position.

Fourth Pass

Key = 4

Now the key element is 14. We will apply binary search in the sorted array to find the position of the key element.

In this scenario, by applying binary search, we can see key element to be placed at index 2 (between 14 and 29). Then we can shift the remaining elements by 1 position.

Now we can see all the elements are sorted.


def binary_search(arr, key, start, end):
    if start == end:
        if arr[start] > key:
            return start
        else:
            return start+1
 
    if start > end:
        return start
 
    mid = (start+end)//2
    if arr[mid] < key:
        return binary_search(arr, key, mid+1, end)
    elif arr[mid] > key:
        return binary_search(arr, key, start, mid-1)
    else:
        return mid
 
def insertion_sort(arr):
    total_num = len(arr)
    for i in range(1, total_num):
        key = arr[i]
        j = binary_search(arr, key, 0, i-1)
        arr = arr[:j] + [key] + arr[j:i] + arr[i+1:]
    return arr
 

sorted_array = insertion_sort([29, 10, 14, 37, 14])
print("Sorted Array : ", sorted_array)

Complexity Analysis

Worst Case

For inserting the i-th element in its correct position in the sorted, finding the position (pos) will take O(log i) steps. However, to insert the element, we need to shift all the elements from pos to i-1. This will take i steps in the worst case (when we have to insert at the starting position).

We make a total of N insertions. so, the worst-case time complexity of binary insertion sort is O(N^2).

This occurs when the array is initially sorted in descending order.

Best Case

The best case will be when the element is already in its sorted position. In this case, we don’t have to shift any of the elements; we can insert the element in O(1).

But we are using binary search to find the position where we need to insert. If the element is already in its sorted position, binary search will take (log i) steps. Thus, for the i-th element, we make (log i) operations, so its best-case time complexity is O(N log N).

This occurs when the array is initially sorted in ascending order.

Average Case

For average-case time complexity, we assume that the elements of the array are jumbled. Thus, on average, we will need O(i /2) steps for inserting the i-th element, so the average time complexity of binary insertion sort is O(N^2).

Space Complexity Analysis

Binary insertion sort is an in-place sorting algorithm. This means that it only requires a constant amount of additional space. We sort the given array by shifting and inserting the elements.

Therefore, the space complexity of this algorithm is O(1) if we use iterative binary search. It will be O(logN) if we use recursive binary search because of O(log N) recursive calls.

Is Binary Insertion Sort a stable algorithm

It is a stable sorting algorithm, the elements with the same values appear in the same order in the final array as they were in the initial array.

Cons and Pros

  1. Binary insertion sort works efficiently for smaller arrays.
  2. This algorithm also works well for almost-sorted arrays, where the elements are near their position in the sorted array.
  3. However, when the size of the array is large, the binary insertion sort doesn’t perform well. We can use other sorting algorithms like merge sort or quicksort in such cases.
  4. Making fewer comparisons is also one of the strengths of this sorting algorithm; therefore, it is efficient to use it when the cost of comparison is high.
  5. Its efficient when the cost of comparison between keys is sufficiently high. For example, if we want to sort an array of strings, the comparison operation of two strings will be high.

Bonus Section

Binary Insertion Sort has a quadratic time complexity just as Insertion Sort. Still, it is usually faster than Insertion Sort in practice, which is apparent when comparison takes significantly more time than swapping two elements.

A simple guide to building REST API’s in GO

In this post we will build Β simple REST API’s using the Go programming language. We will also be using the MUX Router. I will also explain some of the fundamentals of the language for beginners.

If you want to learn Go visit awesome-go-in-education. A curated list of resources about Go in Education. If you want to do the same but in Python read A simple guide to creating REST API’s with flask. I will be using Goland from jetbrains as my IDE.

Before we get started, a few jargon.

REST: a RESTful API uses HTTP requests to GET, PUT, POST and DELETE data.

RESTful API designing: guidelines is a must read before you continue. It talks about terminologies, endpoints, versioning status codes and so much more.

Test your environment

Let us first test the environment to check if everything is working fine. For that we will be using a simple β€œHello World” program.

Running β€œHello World” program

Once that is done, let us import necessary packages.

Performing imports

Let us look at the imports used one by one.

  1. encoding/json – since our API’s communications will be handled in JSON format
  2. log – will log errors
  3. net/http – We will use this package to create the API’s and communicate using HTTP protocols.
  4. mux – Β A powerful URL router and dispatcher for golang . A router is used to define which function will run when a particular endpoint(URL) is called.

Writing the main funciton

Do note Β In Go, := is for declaration + assignment, whereas = is for assignment only.For example, var foo int = 10 is the same as foo := 10.

  1. First we create a new variable for our multiplexer.
  2. Then we use HandleFunc to define which function will handle which API endpoint.
  3. With http.ListenAndServe we define the port that your program must listen to continuously.We wrap that around log.Fatal so that all exeptions are logged.

To run your code type the following in your console
go run main.go

If you face an error telling you that mux is not installed then run
go get -u github.com/gorilla/mux in your console.

Post Requests

Photo by Andrik Langfield on Unsplash

Let us now post some data to the server.

Note: Click here to know more about json in Go.

  1. Adding a new function and a function handler.

2. Β Creating structs that will hold our json data.

3. Writing our add function.

Putting it all together

Testing it using postman

Hope this post helped you. If you want more help, feel free to ping me @Ashish_che

❌