Python Django Introduction
In this page:
Introduction to Django
Django is a full-featured, batteries-included web framework aimed at larger applications, bundling an ORM, a built-in admin interface, and an authentication system out of the box -- a deliberate contrast to Flask's minimalism. Install it with pip install django.
Example: Introduction to Django
# pip install django
import django
print(django.get_version())
Defining Django Views
A Django view is a Python function (or class) that accepts an incoming web request and returns a web response, most commonly as an HttpResponse object. Views hold the actual logic for what happens when a particular URL is visited.
Example: Defining Django Views
from django.conf import settings
settings.configure()
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
response = home(None)
print(response.content)
Django Routing with Paths
Django centralizes URL routing in a Python list called urlpatterns, where each entry maps a URL path to a view using the path() helper function. Keeping all routes declared in one place makes it easy to see a project's entire URL structure at a glance.
Example: Django Routing with Paths
# urls.py
# from django.urls import path
# urlpatterns = [path("home/", home_view)]
print("urlpatterns maps URL paths to view functions")
Creating Django Templates Concept
Templates separate a page's HTML structure from the Python logic that populates it with data, keeping presentation markup in dedicated .html files rather than mixed into view code. Django's template language lets you insert dynamic values and simple control flow directly into otherwise-static HTML.
Example: Creating Django Templates Concept
# templates/home.html would contain:
# <h1>{{ title }}</h1>
print("Templates keep HTML separate from view logic")
Using Django JSONResponse
JsonResponse is a specialized HttpResponse subclass built for API endpoints: pass it a Python dictionary and it automatically serializes that data to JSON and sets the correct Content-Type header, sparing you from calling json.dumps() and setting headers manually.
Example: Using Django JSONResponse
from django.conf import settings
settings.configure()
from django.http import JsonResponse
response = JsonResponse({"status": "ok"})
print(response.content)
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Python NumPy Introduction
- Python NumPy Arrays
- Python Pandas Introduction
- Python Pandas DataFrame
- Python Matplotlib Basics
- Python Data Visualization
- Python Statistics Module
- Python CSV & Data Analysis
- Python requests Module
- Python JSON & APIs
- Python Web Scraping Basics
- Python Flask Introduction
- Python Django Introduction
- Python MongoDB