Django URLs and Routing
# CHAPTER 6
Django URLs and Routing
1. Introduction
When a user typeswww.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.pyfile.
-
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.
A delivery driver arrives at the front desk (The Project
urls.py). They have a package for the "Blog Department".
-
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')).
-
3.
The driver goes to the 2nd Floor (The App
urls.py).
- 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. Openblog/views.py and write a simple Python function that returns an HTTP Response.
*(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
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.
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:
In blog/views.py:
*If a user visits /blog/article/99/, the browser prints: "You are reading Article #99".*
8. Backend Workflow: Naming URLs
Notice thename='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 visitshttp://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 Mastercore/urls.pyfile. While this works technically, it violates Django's modularity rule. If you do this, and later want to copy yourblogapp to a new project, the URLs will be left behind! Always useinclude().
11. Exercises
-
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.pyorblog/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.pythat captures a *string* instead of an integer. The path should look likepath('author/<str:name>/', ...)and the View function should returnHttpResponse("Viewing profile for: [name]").
13. MCQs with Answers
What is the purpose of the include() function in the Master core/urls.py file?
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 inpath()). Why is it an architectural best practice to use URL names instead of hardcoding absolute paths in your templates?
-
Q: Compare
path()with the olderrepath()(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 usinginclude() 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 viaHttpResponse is ugly. We need to send actual HTML web pages to the user. Proceed to Chapter 7: Django Views and Templates.