Python Tutorial

Django Introduction

Django is a high-level Python web framework for building secure, database-backed websites quickly. This section walks through a complete members app, one chapter at a time.

What Is Django?

Django follows the MVT pattern: Model, View, Template. You describe data as Python classes, write views that handle requests, and render HTML templates. Django fills in the rest: URL routing, an ORM, an admin site, forms, authentication, and security defaults.

  • Model — the database table, defined in Python.
  • View — the function (or class) that receives a request and returns a response.
  • Template — HTML with tags that insert data from the view.

Why Django?

  • Batteries included: admin, auth, sessions, CSRF protection, and migrations ship with the framework.
  • The ORM talks to SQLite, PostgreSQL, MySQL, and more without raw SQL for common work.
  • Projects scale from a weekend prototype to a production site.

This tutorial uses a project named mysite and an app named members. Follow every chapter in order and you will have a working CRUD site by the end.

What You Will Build

A members directory where you can:

  1. Create a project and a members app.
  2. Define a Member model and migrate it to SQLite.
  3. Insert, update, and delete rows from the shell and from views.
  4. List members in templates, handle 404 pages, and serve CSS.
  5. Add forms and login so only staff can change data.

Chapters in This Section

ChapterYou will learn
Get StartedPrerequisites and how to check Python
Virtual EnvironmentIsolate Django from other Python projects
Install DjangoInstall the framework with pip
Create Projectstartproject, files, and runserver
Create Appstartapp and INSTALLED_APPS
ViewsReturn HTML from a view function
URLsMap paths to views with path() and include()
TemplatesRender HTML files with context
ModelsDefine tables and run migrations
Insert DataCreate rows with the ORM
Update DataChange a saved object
Delete DataRemove rows
Update ModelAdd fields and migrate again
AdminCreate a superuser and register models
404 TemplateCustom page-not-found responses
Template Variables{{ output tags
Template TagsLogic with {% tags
If TagConditions in templates
For TagLoop over querysets
Include TagReusable navbar and footer
QuerySetall(), count(), laziness
QuerySet GetFetch one object by id
QuerySet FilterLookups like __contains
QuerySet Order BySort results
Static FilesCSS, images, and collectstatic
FormsModelForm, CSRF, POST
AuthenticationLogin, logout, and protected views

Requirements

  • Python 3.10 or newer.
  • pip and a terminal (PowerShell, bash, or cmd).
  • A code editor such as VS Code or Cursor.

The MVT Pattern

Django follows Model-View-Template, its take on MVC:

PartResponsibility
ModelData structure & database access (an ORM class)
ViewBusiness logic — receives a request, returns a response
TemplateHTML with placeholders for dynamic data
URLsMap a URL path to a view

Project Setup at a Glance

pip install django
django-admin startproject mysite
cd mysite
python manage.py startapp members     # create an app
python manage.py migrate               # set up the database
python manage.py runserver             # http://127.0.0.1:8000/

A Django project is the whole site; an app is a reusable feature inside it (e.g. a blog, a members list). One project can contain many apps.

Try It Yourself

Exercise 1: Which command creates a new app called blog?

Show solution
python manage.py startapp blog

Exercise 2: After changing a model, which two commands update the database?

Show solution
python manage.py makemigrations
python manage.py migrate

Key Takeaways

  • Django is a batteries-included web framework using the MVT pattern.
  • A project holds one or more apps.
  • manage.py runs the server, migrations, and admin tasks.
  • The ORM lets you query the database with Python instead of SQL.

📘 Real-World Deep Dive

Django is the "batteries-included" Python web framework: ORM, admin, auth, forms, templates, migrations, and a powerful URL router. Pair the parts and you can ship a CRUD + REST API in a single weekend.

Real-Life Scenario

A small blog: model + admin + view + URL + template, end to end. After this exercise, you will have the full Django mental model in 50 lines of code.

Real-Life Example

# models.py
from django.db import models

class Post(models.Model):
    title  = models.CharField(max_length=200)
    slug   = models.SlugField(unique=True)
    body   = models.TextField()
    pub    = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey("auth.User", on_delete=models.CASCADE)

    class Meta:
        ordering = ["-pub"]
        indexes  = [models.Index(fields=["pub"])]

    def __str__(self):
        return self.title

# views.py
from django.shortcuts import get_object_or_404, render
from .models import Post

def post_list(request):
    posts = Post.objects.select_related("author").order_by("-pub")[:50]
    return render(request, "blog/list.html", {"posts": posts})

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug)
    return render(request, "blog/detail.html", {"post": post})

# urls.py
from django.urls import path
from . import views
urlpatterns = [
    path("",       views.post_list,   name="list"),
    path("<slug:slug>/", views.post_detail, name="detail"),
]

# templates/blog/list.html — minimal
# {% for p in posts %}
#   <article><h2><a href="{% url 'detail' p.slug %}">{{ p.title }}</a></h2>
#   <p>{{ p.pub|date:"Y-m-d" }} — {{ p.body|truncatewords:30 }}</p></article>
# {% endfor %}

Expected Output

(runnable via manage.py runserver; the queryset from Post.objects.select_related(...) is rendered by the template)

Common mistakes

  • Calling .all() on a 1 M-row table loads every row — use .iterator() for streaming.
  • N+1: post.author.name inside a loop triggers one query per post; switch to select_related.
  • Forgetting on_delete=models.CASCADE silently breaks deletes once you migrate.

🚀 Performance & Best Practices

  • Add DB indexes on columns used in filter() — they cost nothing to define and pay off.
  • Set CONN_MAX_AGE in settings.py to keep long-lived DB connections warm.
  • Cache the rendered list view with @cache_page(60 * 5) if reads dominate writes.

🧪 Try It Yourself

  1. Add a /api/posts/ JSON endpoint using DRF.
  2. Add user login + a "create post" form.
  3. Deploy with gunicorn + nginx and confirm collectstatic works.

FAQ: Django Introduction

Common questions about this page.

What is Django Introduction?

Django Introduction is a Django lesson that explains django introduction in Django. Django is a high-level Python web framework for building secure, database-backed websites quickly. This section walks through a complete members app, one... It is written for beginners who want a clear definition and working examples.

Should I run django introduction examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn django introduction in this Django Django lesson (Django Introduction).

How do I use django introduction in Django?

To use django introduction in Django, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of django introduction?

This Django Introduction tutorial shows django introduction syntax with short Django examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Django Introduction example for beginners

Yes. This page includes a beginner django introduction example you can copy and run. It is designed for searches such as "django introduction for beginners", "django introduction example", and "how to use django introduction".

What are common mistakes with django introduction?

Common django introduction mistakes include wrong syntax, mixing types, and skipping practice. Work through this Django chapter in order, run every example, and check the output before moving on.

Why should I learn django introduction?

Django Introduction is used in real Django work. Learning django introduction helps you write clearer programs and continue the Django tutorial on StudyGrid.

Is Django Introduction free to learn online?

Yes. You can learn django introduction free on StudyGrid (studygrid.in). This chapter is part of the Django path and includes examples, syntax, and next-step links.