Python Java C++ HTML CSS Bootstrap JavaScript jQuery AngularJS React Node.js TypeScript Django NumPy Pandas Matplotlib Seaborn Machine Learning Deep Learning Decipher XML

Introduction to Django

Django is a high-level Python web framework designed for rapid development of secure, scalable, and maintainable web applications. It provides batteries-included tooling so you can focus on business logic instead of reinventing common web patterns.

Django ships with an ORM, authentication, admin, forms, validation, and templating out of the box. This makes it especially strong for data-driven websites and APIs where consistency, security, and speed of development matter.

πŸš€ Django follows the MVT (Model–View–Template) architecture. The Model handles data, Views contain the request/response logic, and Templates render HTML.

Why Django?

  • Fast development with built-in conventions and tools
  • Secure by default (CSRF, SQL injection protection, XSS mitigation)
  • Scalable and production-ready with caching, middleware, and async views
  • Powerful ORM for database modeling and migrations
  • Rich ecosystem and real-world adoption (Instagram, Pinterest, Mozilla)

Django Installation

      # Check Python version
      python --version

      # Install Django
      pip install django

      # Verify installation
      django-admin --version
        

Use a virtual environment to isolate dependencies and keep your project reproducible.

      # Create and activate a virtual environment
      python -m venv .venv
      source .venv/bin/activate  # macOS/Linux
      # .venv\\Scripts\\activate  # Windows

      # Pin Django version
      pip install "Django>=4.2,<5.1"
      pip freeze > requirements.txt
        
πŸ“Œ Recommended Python version: 3.9+

Create Django Project

      django-admin startproject myproject
      cd myproject
      python manage.py runserver
        

The project contains global settings and entry points for ASGI/WSGI. The manage.py script is your main command interface.

Project Structure

      myproject/
       β”œβ”€β”€ manage.py
       β”œβ”€β”€ myproject/
       β”‚   β”œβ”€β”€ settings.py
       β”‚   β”œβ”€β”€ urls.py
       β”‚   β”œβ”€β”€ asgi.py
       β”‚   └── wsgi.py
        

Key files:

  • settings.py defines apps, middleware, templates, database, and security settings
  • urls.py routes requests to apps
  • asgi.py enables async servers and WebSockets
  • wsgi.py is the production entry point for WSGI servers

Create Django App

      python manage.py startapp core
        

Apps are reusable, modular units. Organize your project by domain (e.g., blog, accounts) instead of by file type.

App Structure

      core/
       β”œβ”€β”€ admin.py
       β”œβ”€β”€ apps.py
       β”œβ”€β”€ models.py
       β”œβ”€β”€ views.py
       β”œβ”€β”€ tests.py
        
βœ” Always add app in INSTALLED_APPS

URL Routing

URLs map browser requests to views. Django resolves patterns in order and stops at the first match.

      # core/urls.py
      from django.urls import path
      from . import views

      urlpatterns = [
        path('', views.home, name='home'),
      ]
        
      # myproject/urls.py
      from django.urls import path, include

      urlpatterns = [
        path('', include('core.urls')),
      ]
        

Advanced routing features include path converters, namespacing, and reverse URL lookup.

      path('users//', views.profile, name='profile')
      app_name = "core"
      # Reverse lookup: reverse('core:profile', args=[1])

Views

Views handle request logic and return responses. They can return HTML, JSON, redirects, or files.

      from django.http import HttpResponse

      def home(request):
          return HttpResponse("Hello Django")
        
      from django.shortcuts import render

      def about(request):
          return render(request, 'about.html')
        

Use JsonResponse for API responses and handle methods explicitly.

      from django.http import JsonResponse

      def api_status(request):
          return JsonResponse({"ok": True})

Templates

      templates/
       └── core/
           └── home.html
        
      
      

Welcome

      def home(request):
          return render(request,'core/home.html',{'name':'Django'})
        

Templates support inheritance, filters, and template tags to keep layouts consistent.

      
      {% block content %}{% endblock %}

      
      {% extends "base.html" %}
      {% block content %}

{{ name|upper }}

{% endblock %}

Static Files (CSS, JS, Images)

      static/
       β”œβ”€β”€ css/style.css
       β”œβ”€β”€ js/app.js
       └── images/logo.png
        
      
      <link rel="stylesheet" href="/static/css/main.css?v=20260308">
        

In production, collect static files to a single directory using collectstatic and serve them via a web server or CDN.

Models & Database

      from django.db import models

      class Student(models.Model):
          name = models.CharField(max_length=100)
          age = models.IntegerField()
          email = models.EmailField()

          def __str__(self):
              return self.name
        
      python manage.py makemigrations
      python manage.py migrate
        

Models define database schema and relationships. Use ForeignKey, ManyToManyField, and OneToOneField to model data.

      class Course(models.Model):
          title = models.CharField(max_length=120)

      class Enrollment(models.Model):
          student = models.ForeignKey(Student, on_delete=models.CASCADE)
          course = models.ForeignKey(Course, on_delete=models.CASCADE)

Django ORM (Database Queries)

      Student.objects.create(name="Ali", age=20)
      Student.objects.all()
      Student.objects.filter(age__gt=18)
      Student.objects.get(id=1)
        
      Student.objects.update(age=22)
      Student.objects.delete()
        

QuerySets are lazy and chainable. Use select_related and prefetch_related to reduce database queries.

      Student.objects.select_related().filter(age__gte=18)
      Student.objects.prefetch_related('enrollment_set')

Django Admin Panel

      python manage.py createsuperuser
        
      from django.contrib import admin
      from .models import Student

      admin.site.register(Student)
        

Customize the admin with ModelAdmin to improve search, filters, and list display.

      @admin.register(Student)
      class StudentAdmin(admin.ModelAdmin):
          list_display = ("name", "age", "email")
          search_fields = ("name", "email")
          list_filter = ("age",)

Forms & ModelForms

      from django import forms
      from .models import Student

      class StudentForm(forms.ModelForm):
          class Meta:
              model = Student
              fields = '__all__'
        
      def add_student(request):
          form = StudentForm(request.POST or None)
          if form.is_valid():
              form.save()
          return render(request,'form.html',{'form':form})
        

Forms support validation via clean() and field-specific clean_field methods. Always include CSRF tokens in templates.

      
      

Authentication (Login / Signup)

      from django.contrib.auth import authenticate, login, logout
        
      user = authenticate(username=u, password=p)
      login(request, user)
      logout(request)
        
πŸ” Django provides secure authentication by default

Use permissions and groups to manage access, and consider a custom user model early for extensibility.

Middleware

Middleware processes requests before views and responses after views. Order matters and can affect performance and security.

      MIDDLEWARE = [
       'django.middleware.security.SecurityMiddleware',
       'django.contrib.sessions.middleware.SessionMiddleware',
      ]
        

Custom middleware lets you add logging, auth checks, or request timing.

Class Based Views (CBV)

      from django.views import View
      from django.http import HttpResponse

      class HomeView(View):
          def get(self, request):
              return HttpResponse("Hello CBV")
        

CBVs provide reusable patterns like ListView, DetailView, CreateView, and mixins for auth and permissions.

Django REST Framework (API)

      pip install djangorestframework
        
      from rest_framework import serializers

      class StudentSerializer(serializers.ModelSerializer):
          class Meta:
              model = Student
              fields = '__all__'
        

DRF adds viewsets, routers, permissions, authentication, and pagination to build robust APIs quickly.

Security Best Practices

  • CSRF Protection
  • Password Hashing
  • SQL Injection Prevention
  • XSS Protection

Also configure SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, and keep SECRET_KEY out of source control.

Deployment

  • Gunicorn
  • Nginx
  • Docker
  • Heroku / AWS
      DEBUG = False
      ALLOWED_HOSTS = ['yourdomain.com']
        

Use environment variables for secrets, configure database URLs, and run collectstatic before deploying.