Django

Language: Python

Web

Django was created by Adrian Holovaty and Simon Willison in 2005 at the Lawrence Journal-World newspaper. Its goal was to simplify web development by providing reusable components and a 'batteries-included' philosophy. Over time, it became one of the most widely used Python frameworks for building scalable, secure web applications.

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It includes built-in tools for database ORM, authentication, templating, routing, and an admin interface.

Installation

pip: pip install django
conda: conda install django

Usage

Django enables developers to quickly create web applications with structured models, views, templates, and URLs. It provides an admin interface out-of-the-box and includes features like authentication, sessions, forms, and security mechanisms.

Creating a new project

# Terminal commands
django-admin startproject mysite
cd mysite
python manage.py runserver

Starts a new Django project named 'mysite'. Running the server starts a local development server at http://127.0.0.1:8000/.

Creating a new app

# Terminal commands
python manage.py startapp blog

Creates a new Django app called 'blog' inside your project. Apps encapsulate related models, views, and templates.

Defining models and migrations

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

Defines a Post model. Use `python manage.py makemigrations` and `python manage.py migrate` to create the database schema.

Views and URL routing

from django.shortcuts import render
from django.urls import path

# views.py
def home(request):
    return render(request, 'home.html')

# urls.py
urlpatterns = [path('', home, name='home')]

Defines a view function `home` and maps it to the root URL. Django uses URLconf to connect URLs to views.

Using the Django Admin Interface

# Register model in admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)

Adds your model to the admin interface so you can manage database records through the built-in web UI.

Error Handling

OperationalError: Ensure migrations are applied and database is accessible.
TemplateDoesNotExist: Check the template directory settings and file paths.

Best Practices

Keep apps modular and reusable.

Use Django's built-in authentication and permission system for security.

Leverage class-based views for complex logic.

Separate settings for development and production.

Use environment variables for sensitive data.