Django Tutorial menu

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

bash
python manage.py startapp courses

This 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

python
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

python
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

python
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

python
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:

URLView
/courses/index
/courses/about/about
/admin/Django admin
Output
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

python
# 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

python
# 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:

Output
Course 2: Graphic Designing
ConverterMatches
<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

python
def search(request):
    q = request.GET.get("q", "")
    return HttpResponse(f"You searched for: {q}")
Output
You searched for: python

Exercise

Exercise

Which function adds an app's URL patterns into the main urls.py?

Learn Django with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp