URLs and views
A view is a Python function that takes a request and returns a response. A URL pattern connects an address to a view.
Your first view
In an app (created with python manage.py startapp courses, and added to INSTALLED_APPS), edit courses/views.py:
Python
from django.http import HttpResponse
def home(request):
return HttpResponse("<h1>Welcome to CodeMIRAI</h1>")
def about(request):
return HttpResponse("We teach coding in small steps.")Connecting URLs
Create courses/urls.py:
Python
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("about/", views.about, name="about"),
]Then include the app's URLs in the project's config/urls.py:
Python
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("courses.urls")),
]Now / shows the home view and /about/ the about view.
Capturing values from the URL
Angle brackets capture part of the URL and pass it to the view as an argument:
Python
# courses/urls.py
urlpatterns = [
path("", views.home, name="home"),
path("courses/<slug:slug>/", views.course_detail, name="course-detail"),
path("lessons/<int:number>/", views.lesson, name="lesson"),
]Python
# courses/views.py
from django.http import HttpResponse
def course_detail(request, slug):
return HttpResponse(f"You are viewing the course: {slug}")
def lesson(request, number):
return HttpResponse(f"Lesson number {number}, doubled is {number * 2}")Converters check and convert the value:
| Converter | Matches | Example |
|---|---|---|
str | any text without / (the default) | <str:name> |
int | zero or positive whole numbers | <int:id> |
slug | letters, numbers, hyphens, underscores | <slug:slug> |
uuid | a UUID | <uuid:token> |
/lessons/7/ calls lesson(request, number=7) with 7 as an int; /lessons/abc/ doesn't match at all, so Django returns a 404.
Names instead of hard-coded URLs
The name= lets you build URLs from code, so changing a URL later doesn't break links:
Python
from django.urls import reverse
reverse("course-detail", args=["python"]) # "/courses/python/"In templates you'll write {% url 'course-detail' 'python' %}.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.