🎓 A1Learner
🔍
0 of 50 lessons completed

Including App URLs

The include function brings the address rules of an app into a project. The project file stays short, and each app keeps its own rules.

The app patterns

This list holds the blog addresses. The empty string means the blog home.

blog_patterns = [path("", blog_home), path("post/", blog_post)]

Include them

This pattern brings the blog list into the project under blog/.

urlpatterns = [path("blog/", include(blog_patterns))]

Ask for the blog home

The test client asks for the blog home. The project prefix joins the empty blog address.

print(client.get("/blog/").content.decode())

Ask for a blog post

The test client asks for a blog post. The prefix joins the post address.

print(client.get("/blog/post/").content.decode())

Example

import django
from django.conf import settings

settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()

from django.http import HttpResponse
from django.urls import include, path


def blog_home(request):
    return HttpResponse("Blog home")


def blog_post(request):
    return HttpResponse("Blog post")


blog_patterns = [path("", blog_home), path("post/", blog_post)]
urlpatterns = [path("blog/", include(blog_patterns))]

from django.test import Client

client = Client()
print(client.get("/blog/").content.decode())
print(client.get("/blog/post/").content.decode())

Key points

  • Use include to bring another list of patterns into urlpatterns.
  • The project pattern names the address prefix, like blog/.
  • The included list holds the addresses under that prefix.
  • Each app keeps its own pattern list.
  • The full address joins the prefix and the included address.

In this example, the setup lines configure Django. The blog list holds two patterns, one for the home and one for a post. The project list includes the blog list under blog/. The test client asks for both addresses and prints the pages.

Note

Include takes the list, not a single pattern.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does include do?