Django: Essentials

Django: Essentials

July 10, 2024

Django: a beautiful Python web framework. Each time I explore it, I uncover fascinating functionalities. I believe the beauty lies in the M-V-T software design pattern that facilitates the development of creating complex, database-driven sites.

Though the framework is vast, and my knowledge limited, I will share essentials of Django in this blog.

Features

  • Fast and Reliable
  • Built for Python 3.x
  • Customizable & Extensible
  • Secure and Scalable
  • Modular structure
  • Batteries included - offers built-in solutions and features for basically all problems.
  • Production-ready for building websites.

Set up & Run

  • Install the package
pip install django
  • Creating the project
django-admin startproject <project-name>

To understand the structure of a Django Project, you can read this blog post

  • Run the server
python manage.py runserver

Creating your first app

  • An app is a module that enforces code reusability.
python manage.py startapp <app-name>

Models

  • Python classes that represent database tables.
from django.db import models

class MyModel(models.Model):
    field1 = models.CharField(max_length=100)
    field2 = models.IntegerField()

After defining models, create database tables based on your models by running migrations:

python manage.py makemigrations
python manage.py migrate

Views

  • used to build concrete logic / function / class to execute different urls.
  • load & prepare data.
  • run any other business logic.
  • prepare & return response data ( Ex: HTML)

Creating your first view

from django.http import HttpResponse


def first_view(request):
    return HttpResponse("Hello, world.")

URLs

  • mapping incoming requests to specific views / functions to handle requests.

Adding URL in the app

from django.urls import path

from . import views

urlpatterns = [
    path("january", views.first_view)  # views.function_name
]

Adding URL in the project directory

from django.contrib import admin
from django.urls import path
from django.urls import include  # import this

urlpatterns = [
    path('admin/', admin.site.urls),
    path("challenge/", include("challenge.urls"))  #appname.urls
]