Django Apps, Views and URLs
A project is split into apps. Each app does one job, and its views answer the visitor's requests.
Project vs App
- A project is the whole website
- An app is one part of it, such as a blog, a shop or a courses section
- One project can have many apps, and an app can be reused in other projects
Create an App
Example
python manage.py startapp coursesThis creates a courses folder with files like views.py, models.py, admin.py and apps.py. Then tell the project about it in settings.py:
Example
INSTALLED_APPS = [
# ... the default apps ...
"courses",
]Forgetting to add your app to INSTALLED_APPS is a very common mistake. Its models and templates will not be found.
Write a View
A view is a function that takes a request and returns a response. Edit courses/views.py:
Example
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1>Our Courses</h1><p>Web, Graphics and SEO.</p>")
def about(request):
return HttpResponse("Workownix is an IT institute in Karachi.")Connect URLs
Create a new file courses/urls.py:
Example
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="course-list"),
path("about/", views.about, name="about"),
]Then include it in the main mysite/urls.py:
Example
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("courses/", include("courses.urls")),
]Now these addresses work:
| URL | View |
|---|---|
/courses/ | index |
/courses/about/ | about |
/admin/ | Django admin |
Our Courses Web, Graphics and SEO.
Values from the URL
Use angle brackets to capture part of the URL and pass it to the view:
Example
# courses/urls.py
urlpatterns = [
path("", views.index, name="course-list"),
path("<int:course_id>/", views.detail, name="course-detail"),
path("city/<str:city>/", views.by_city, name="by-city"),
]Example
# courses/views.py
from django.http import HttpResponse, Http404
COURSES = {1: "Web Development", 2: "Graphic Designing", 3: "SEO"}
def detail(request, course_id):
if course_id not in COURSES:
raise Http404("Course not found")
return HttpResponse(f"Course {course_id}: {COURSES[course_id]}")
def by_city(request, city):
return HttpResponse(f"Courses available in {city.title()}")Visiting /courses/2/ shows:
Course 2: Graphic Designing
| Converter | Matches |
|---|---|
<int:x> | Whole numbers like 5 |
<str:x> | Any text without a slash |
<slug:x> | Letters, numbers, hyphens like web-design |
Query Strings
Values after ? are in request.GET. For /courses/search/?q=python:
Example
def search(request):
q = request.GET.get("q", "")
return HttpResponse(f"You searched for: {q}")You searched for: python
Exercise
Exercise
Which function adds an app's URL patterns into the main urls.py?
