Project, Apps and First View

First lesson of the Django Fundamentals course, free to read: about 18 minutes, 3 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Create a Django project and an app, and understand their respective roles
  • Write a function view and link it to a URL with path() and include()
  • Understand the request → URL → view → response cycle and the MTV architecture

Project and appsURL routingViews

Django in brief

Django is a “batteries included” Python web framework: ORM for the database, template system, forms, authentication, admin interface, security protections… It is used for content sites, back offices, SaaS and APIs. This course uses Django 6.1 (which requires Python 3.12 or newer); the concepts presented are the same in the long-term support version 5.2 LTS.

Creating a project

python -m venv .venv && source .venv/bin/activate
python -m pip install Django            # latest stable version (6.1)
django-admin startproject config .     # the dot: creates the project in the current folder
python manage.py runserver              # http://127.0.0.1:8000

Resulting directory structure:

manage.py            project command tool
config/
    settings.py      configuration (apps, database, language...)
    urls.py          main URL table
    wsgi.py, asgi.py entry points for production servers

In settings.py, set LANGUAGE_CODE = "fr-fr" and TIME_ZONE = "Europe/Paris".

Creating an app

A project is a site; an app is a module that handles a feature (catalog, blog, accounts). A project contains several.

python manage.py startapp catalogue

Then declare it in config/settings.py:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    # ... apps provided by Django ...
    "catalogue",            # our app
]

First view

A view is a function that receives a request (HttpRequest) and returns a response (HttpResponse).

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


def accueil(request):
    return HttpResponse("<h1>Bienvenue dans le catalogue</h1>")


def detail_produit(request, pk):        # pk comes from the URL, already converted to int
    return HttpResponse(f"Produit n°{pk}")

Linking URLs to views

# catalogue/urls.py (file to create)
from django.urls import path
from . import views

app_name = "catalogue"                   # namespace for the app's URLs
urlpatterns = [
    path("", views.accueil, name="accueil"),
    path("produits/<int:pk>/", views.detail_produit, name="detail"),
]
# config/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("catalogue/", include("catalogue.urls")),   # delegates everything starting with catalogue/
]

<int:pk> is a converter: it only accepts digits and passes an int to the view. The others: str (default, anything except /), slug (letters, digits, hyphens, underscores), uuid, path (also accepts /). /catalogue/produits/abc/ matches no pattern: Django returns 404.

The name parameter lets you generate URLs without hard-coding them: reverse("catalogue:detail", args=[3]) gives /catalogue/produits/3/.

The journey of a request

  1. The browser requests /catalogue/produits/3/.
  2. Django goes through config/urls.py in order, finds catalogue/, then continues in catalogue/urls.py with produits/3/.
  3. The first matching pattern wins: Django calls detail_produit(request, pk=3).
  4. The view returns an HttpResponse (often built from a model and a template).

This is the MTV architecture: the Model handles data, the Template presentation, the View logic. URL dispatching is handled by the framework.

Key takeaways

  • startproject once, startapp per feature, without forgetting INSTALLED_APPS.
  • View = function request → HttpResponse.
  • path() + converters + name, and include() for each app.

Exercises

Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.

  1. CodeDifficulty 3Python in the browser2 hints

    Resolve a URL like Django

    Implement the core of routing:

    • compiler(route) turns a route like "produits/<int:pk>/" into (compiled regex, conversions) handling <int:x>, <slug:x>, <str:x>, <path:x> and <x> (equivalent to str);
    • resoudre(urlpatterns, chemin) receives a list of (route, nom) and a path like "/produits/3/", removes the leading /, tests the patterns in order and returns (nom, kwargs) with the converted values, or None (404).

    Patterns: int [0-9]+, slug [-a-zA-Z0-9_]+, str [^/]+, path .+.

    import re
    
    CONVERTISSEURS = {
        "int": (r"[0-9]+", int),
        "slug": (r"[-a-zA-Z0-9_]+", str),
        "str": (r"[^/]+", str),
        "path": (r".+", str),
    }
    
    
    def compiler(route):
        ...
    
    
    def resoudre(urlpatterns, chemin):
        ...
  2. TaskDifficulty 12 hints

    Create the project and the catalogue app

    In your working environment: create a venv, install Django (python -m pip install Django), run django-admin startproject config ., then python manage.py startapp catalogue. Add the app to INSTALLED_APPS, create catalogue/urls.py with the accueil and detail_produit views, include it under catalogue/ in config/urls.py and run python manage.py runserver.

    • /catalogue/ displays the welcome message
    • /catalogue/produits/7/ displays "Produit n°7"
    • /catalogue/produits/abc/ returns a 404 page
    • LANGUAGE_CODE is fr-fr and the development error page is in French
  3. Multiple choiceDifficulty 11 hint

    Project or app?

    After python manage.py startapp blog, what do you need to do for Django to take the models of blog into account?

    • Nothing, it's automatic
    • Add "blog" to INSTALLED_APPS
    • Run startproject again
    • Create a blog.py file at the root

End-of-lesson quiz

  1. What does a Django view receive and return?

    • A dict and a string
    • An HttpRequest and an HttpResponse
    • A URL and a model
  2. What does include(“catalogue.urls”) do?

    • Copies the views
    • Delegates the rest of the URL to the app's URLconf
    • Creates the app
  3. Which converter accepts “mon-article-2026” but not “a/b”?

    • int
    • slug
    • path

The rest of the course

  1. Models and Migrations18 min
  2. Querying Data with the ORM18 min
  3. Views and Templates20 min
  4. Forms and the Admin Interface20 min

Django Fundamentals · Intermediate · 3 h 34 min