← Back to Python Course | Chapter 13: Data Science & Web | Lesson 13 of 14

Python Django Introduction

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

python
# 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

python
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

python
# 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

python
# 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

python
from django.conf import settings
settings.configure()
from django.http import JsonResponse

response = JsonResponse({"status": "ok"})
print(response.content)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.