PYTHON

Python Django: Syntax, Usage, and Examples

Django is a high-level web framework for Python that helps you build secure, data-driven websites and APIs quickly.

It gives you a clear project structure, an ORM, templates, and an admin panel so you can focus on your app’s logic instead of reinventing plumbing.


How to Use Django

Using Django follows a predictable flow: install the framework, create a project, add apps, then connect URLs, views, templates, and models.

1. Install Django

First, install Django into your virtual environment:

pip install django

After this, commands like django-admin and manage.py become available in your project.

2. Create a Project

A project is the top-level container for your site’s settings and global URLs.

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

Visit http://127.0.0.1:8000/ in your browser to see Django’s default welcome page. That confirms the project runs correctly.

3. Create an App

Django splits functionality into smaller pieces called “apps.” A blog, a shop, and an accounts system can all be separate apps inside one project.

python manage.py startapp blog

Then enable the app in mysite/settings.py:

INSTALLED_APPS = [
    # ...
    "blog",
]

This lets Django discover models, templates, and signals defined in that app.

4. Create a View

A view is a Python function or class that accepts a request and returns a response.

# blog/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to the blog!")

This tiny function already counts as a Django view: it takes a request object and returns an HTTP response.

5. Map URLs to Views

Next, hook that view to a URL.

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

urlpatterns = [
    path("", views.home, name="blog-home"),
]

Include the app’s URLs in the project-level routing:

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("blog/", include("blog.urls")),
]

Now http://127.0.0.1:8000/blog/ runs home().

6. Use Templates for HTML

Plain strings are fine for quick tests, but real sites need HTML templates. Django uses a simple templating language.

# blog/views.py
from django.shortcuts import render

def home(request):
    context = {"title": "Blog Home"}
    return render(request, "blog/home.html", context)

Template (HTML5):

<!-- blog/templates/blog/home.html -->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>{{ title }}</title>
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Hello from Django!</p>
  </body>
</html>

The render helper takes the request, a template path, and a context dictionary, then returns a fully rendered HTML response.

7. Define Models and Use the ORM

For data, you define models as Python classes:

# blog/models.py
from django.db import models

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

    def __str__(self):
        return self.title

Run migrations to create the tables:

python manage.py makemigrations
python manage.py migrate

Then query with the ORM:

from .models import Post

latest_posts = Post.objects.order_by("-created_at")[:5]

You work with Python objects instead of writing raw SQL for everyday queries.


When to Use Django

Django is overkill for a tiny script, but great once you move into “real app” territory. Here are common use cases where Django shines.

1. Data-Driven Websites

Any site that stores and displays structured data fits Django well:

  • Blogs, news sites, and content platforms
  • Portfolios with projects and case studies
  • Educational platforms with courses and lessons

You get models, migrations, and a clean way to structure views and templates from day one.

2. Internal Tools and Dashboards

Companies often need internal tools for operations: order management, inventory tracking, HR dashboards, and so on. Django’s admin, forms, and ORM make these quick to build.

You can:

  • Let staff log in and manage records
  • Restrict access to certain models or actions
  • Iterate quickly as your processes change

Instead of wrestling with low-level details, you focus on “what should this tool do for the team?”

3. APIs and Backends for Frontend Apps

Django can serve HTML and JSON side by side. Many teams use it as an API backend for:

  • Single-page apps built with React, Vue, or Svelte
  • Mobile apps that need a central server
  • Third-party integrations that expect JSON endpoints

You can create JSON endpoints with JsonResponse or add Django REST Framework for more advanced API features.

4. Authentication-Heavy Projects

Django ships with batteries for authentication:

  • User model and password hashing
  • Login, logout, and password reset views
  • Permissions and groups

Any app that needs user accounts—forums, learning platforms, ticket systems—can start from these built-in tools instead of rolling its own login system.

5. Projects With Growing Complexity

As your app grows from a side project into something bigger, structure matters. Django nudges you into an organized architecture: apps, clear settings, URL routing, split templates, and reusable components.

That structure helps:

  • Keep things readable for future you
  • Onboard new team members faster
  • Avoid “giant single file” chaos

You spend more time on features and less on taming sprawl.


Examples of Django in Action

Let’s walk through a few small but realistic examples that reveal how the pieces fit together.

Example 1: Personalized Greeting Page

A simple view that reads a query parameter and shows a greeting:

# blog/views.py
from django.shortcuts import render

def greet(request):
    name = request.GET.get("name", "friend")
    return render(request, "blog/greet.html", {"name": name})

Template:

<!-- blog/templates/blog/greet.html -->
<h1>Hello, {{ name }} 👋</h1>
<p>Glad you dropped by.</p>

Users named Arjun, Lena, or Sam all see their own name if they visit /blog/greet/?name=Arjun. This tiny example covers URL parameters, context, templates, and inclusive user-facing text.

Example 2: Listing Blog Posts

Use a model and a list view to show posts:

# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.order_by("-created_at")
    return render(request, "blog/post_list.html", {"posts": posts})

Template:

<!-- blog/templates/blog/post_list.html -->
<h1>Recent posts</h1>
<ul>
  {% for post in posts %}
    <li>
      <h2>{{ post.title }}</h2>
      <p>{{ post.body|truncatechars:150 }}</p>
      <small>Published {{ post.created_at }}</small>
    </li>
  {% empty %}
    <li>No posts yet. Check back soon.</li>
  {% endfor %}
</ul>

Here you see the full path: database → ORM → view → template.

Example 3: JSON Endpoint for Frontend

A basic health-check API endpoint:

# api/views.py
from django.http import JsonResponse

def health(request):
    data = {
        "status": "ok",
        "version": "1.0.0",
    }
    return JsonResponse(data)

URL:

# api/urls.py
from django.urls import path
from .views import health

urlpatterns = [
    path("health/", health, name="health"),
]

This gives you a JSON endpoint like /api/health/ that a frontend app or monitoring tool can call.

Example 4: Form Handling With Validation

Django forms wrap HTML forms and validation together.

# accounts/forms.py
from django import forms

class SignupForm(forms.Form):
    email = forms.EmailField()
    display_name = forms.CharField(max_length=50)

View:

# accounts/views.py
from django.shortcuts import render, redirect
from .forms import SignupForm

def signup(request):
    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            # Save user or send to a service
            return redirect("signup-success")
    else:
        form = SignupForm()

    return render(request, "accounts/signup.html", {"form": form})

Template sketch:

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign up</button>
</form>

This flow handles:

  • Displaying fields
  • Validating input
  • Showing error messages

All with a small amount of code.

Example 5: Admin Configuration

Register models to manage them in the admin panel:

# blog/admin.py
from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ("title", "created_at")
    search_fields = ("title", "body")

The admin gives editors a friendly UI to add and edit posts, search content, and manage data—no raw SQL needed.


Learn More About Django Concepts

Once the basics feel familiar, a few deeper ideas help you use Django more confidently.

Project vs. App

A quick recap:

  • Project: Global configuration (settings, top-level URLs, WSGI/ASGI entry point)
  • App: Focused piece of functionality (blog, accounts, payments, etc.)

One project can contain many apps. Apps can be reused across different projects, which encourages modular design.

MVT Pattern (Model–View–Template)

Django follows the MVT pattern:

  • Model: Defines data structure and behavior (via classes and fields)
  • View: Contains logic for handling requests and returning responses
  • Template: Controls presentation and HTML rendering

This separation keeps business logic out of templates and database details out of views, making large projects easier to maintain.

Migrations and Schema Changes

As your models evolve, migrations track changes to the database schema:

python manage.py makemigrations
python manage.py migrate

You might add a new field, change a length, or create a new model. Migrations keep development, staging, and production databases in sync without manual SQL scripts.

Middlewares

Middlewares are hooks around the request/response cycle. You can use them to:

  • Add security headers
  • Log requests
  • Attach extra data to the request

Django comes with built-in middlewares for sessions, authentication, CSRF protection, and more. You can also write custom ones when you need cross-cutting behavior.

Security Features

Django includes many security features by default:

  • CSRF protection for forms
  • Automatic HTML escaping in templates
  • Protection against SQL injection through the ORM
  • Safe password storage with strong hashing algorithms

These features don’t replace good judgment, but they give you a strong baseline so simple mistakes are less likely to become serious issues.

Extending Django With Packages

The Django ecosystem is huge. Popular extensions include:

  • Django REST Framework for building APIs
  • django-allauth for sign-in with social providers
  • django-debug-toolbar for introspecting queries and performance in development

Combining Django with these libraries lets you build advanced features without re-implementing common patterns.


Summary

Django is a full-featured web framework for Python that helps you build data-driven sites, APIs, and internal tools quickly and safely. You create a project, add apps, define models, views, URLs, and templates, and let Django handle the boring but essential details like migrations, authentication, and security.

Once you get comfortable with the project structure, MVT pattern, and the ORM, Django starts to feel like an extension of regular Python programming.

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.