Skip to main content
Django Basics Tutorial
CHAPTER 06 Beginner

Django URLs and Routing

Updated: May 14, 2026
25 min read

# CHAPTER 6

Django URLs and Routing

1. Introduction

When a user types www.example.com/about/ into their browser, how does Django know which piece of Python code to execute? The answer is Routing. In Django, URLs are the road signs of your application. The URL dispatcher acts as a sophisticated traffic cop, reading the incoming web address and routing it to the appropriate View function. In this chapter, we will learn how to define URL patterns, capture dynamic data from URLs, and link our Project to our Apps.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the role of the urls.py file.
  • Use the path() function to map a URL string to a View.
  • Implement include() to delegate routing from the Project to an App.
  • Capture dynamic URL parameters (e.g., article/5/).

3. Beginner-Friendly Explanation

Imagine your website is a massive office building.
  1. 1. A delivery driver arrives at the front desk (The Project urls.py). They have a package for the "Blog Department".
  1. 2. The receptionist doesn't know where the specific employee is, but they say, "The Blog Department is on the 2nd Floor." (include('blog.urls')).
  1. 3. The driver goes to the 2nd Floor (The App urls.py).
  1. 4. The floor manager looks at the specific package ("Article #42") and directs the driver to the exact desk (The View function).

This two-step process keeps the front desk from getting overwhelmed when the building has 10,000 employees.

4. Step 1: Writing a View Function

Before we can route traffic, we need a destination. Open blog/views.py and write a simple Python function that returns an HTTP Response.
python
12345678
# blog/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("<h1>Welcome to the Blog Homepage!</h1>")

def about(request):
    return HttpResponse("<h1>About Us</h1><p>We write about Django.</p>")

*(Remember: Every View function MUST accept request as its first parameter).*

5. Step 2: The App URLs (Floor Manager)

By default, django-admin does NOT create a urls.py file inside your App. You must create it manually.

Create a new file: blog/urls.py

python
1234567891011
# blog/urls.py
from django.urls import path
from . import views # Import the views.py file from the current folder

urlpatterns = [
    # When someone visits the root of the blog, run views.home
    path(&#039;', views.home, name='blog-home'),
    
    # When someone visits /about/, run views.about
    path(&#039;about/', views.about, name='blog-about'),
]

6. Step 3: The Project URLs (Front Desk)

Now we must tell the Master Project about the App's URLs.

Open core/urls.py. Use the include function to link them.

python
1234567891011
# core/urls.py
from django.contrib import admin
from django.urls import path, include # Add 'include' here

urlpatterns = [
    # The built-in Django Admin Panel
    path(&#039;admin/', admin.site.urls),
    
    # Send any traffic starting with 'blog/' to the blog App's urls.py file
    path(&#039;blog/', include('blog.urls')),
]

Testing it out: Start your server (python manage.py runserver). Visit: http://127.0.0.1:8000/blog/ -> You will see "Welcome to the Blog Homepage!" Visit: http://127.0.0.1:8000/blog/about/ -> You will see "About Us".

7. Dynamic URL Parameters

What if you want to view Article #5? You don't write 1,000 different paths for 1,000 articles. You use dynamic parameters.

In blog/urls.py:

python
12
# The '<int:id>/' captures an integer from the URL and passes it to the view
path(&#039;article/<int:id>/', views.read_article, name='read-article'),

In blog/views.py:

python
123
# The view must accept the 'id' parameter!
def read_article(request, id):
    return HttpResponse(f"<h1>You are reading Article #{id}</h1>")

*If a user visits /blog/article/99/, the browser prints: "You are reading Article #99".*

8. Backend Workflow: Naming URLs

Notice the name='blog-home' argument in Step 5? Never hardcode URLs in your HTML (e.g., <a href="/blog/about/">). If your boss tells you to change the URL from /blog/about/ to /blog/company-history/, you would have to find and replace that string in 50 different HTML files. Instead, Django allows you to use the name. If you link to the *name* in your HTML, Django dynamically calculates the correct URL. If the URL path changes, your HTML links will update automatically!

9. Best Practices

  • Trailing Slashes: Notice how Django URLs almost always end with a slash: path('about/', ...). Django is very strict about this. If a user visits http://mysite.com/about (no slash), Django will automatically redirect them to /about/ for SEO consistency.

10. Common Mistakes

  • Forgetting include(): Beginners often try to import all their App views directly into the Master core/urls.py file. While this works technically, it violates Django's modularity rule. If you do this, and later want to copy your blog app to a new project, the URLs will be left behind! Always use include().

11. Exercises

  1. 1. Trace the Request flow: A user types http://127.0.0.1:8000/blog/article/42/. Explain chronologically which file intercepts the request first (core/urls.py or blog/urls.py), and how the number 42 gets passed to the Python logic.

12. Coding Challenges

  • Challenge: Write a new dynamic path in blog/urls.py that captures a *string* instead of an integer. The path should look like path('author/<str:name>/', ...) and the View function should return HttpResponse("Viewing profile for: [name]").

13. MCQs with Answers

Question 1

What is the purpose of the include() function in the Master core/urls.py file?

Question 2

In the URL pattern path('post/<int:postid>/', views.viewpost), what is the purpose of <int:postid>?

14. Interview Questions

  • Q: Explain the concept of URL namespacing (the name= argument in path()). Why is it an architectural best practice to use URL names instead of hardcoding absolute paths in your templates?
  • Q: Compare path() with the older repath() (Regular Expression path) in Django. When might a developer need to use regular expressions for routing?

15. FAQs

Q: Can I put the blog on the homepage instead of /blog/? A: Yes! In core/urls.py, simply leave the string empty: path('', include('blog.urls')). Now http://127.0.0.1:8000/ will trigger the blog homepage!

16. Summary

In Chapter 6, we mastered traffic direction. We learned how the URL dispatcher intercepts incoming web requests and routes them to specific Python View functions. We adopted the professional best practice of using include() to keep our Project routing cleanly separated from our App routing. Finally, we learned how to capture dynamic data from the URL path to build scalable, data-driven endpoints.

17. Next Chapter Recommendation

Returning raw text via HttpResponse is ugly. We need to send actual HTML web pages to the user. Proceed to Chapter 7: Django Views and Templates.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·