Django Tutorial: Routing 🎯

beginner
15 min

Django Tutorial: Routing 🎯

Welcome back to CodeYourCraft! Today, we're diving into one of the most exciting topics in Django - Routing. By the end of this lesson, you'll have a solid understanding of how Django handles URLs and navigation.

Let's get started!

What is Routing? πŸ“

In web development, routing refers to the process of matching incoming requests to appropriate handlers. Django's routing system is a simple yet powerful feature that makes it easy to organize your URLs and handle different types of requests.

The Django URL Pattern πŸ’‘

The heart of Django's routing system is the URL pattern. A URL pattern defines a series of rules that match a particular URL and assigns it to a view.

A basic URL pattern in Django looks like this:

python
path('<variable>/', views.my_view, name='my_view_name')

Here's what each part means:

  • <variable>: A placeholder for URL components that will be matched and passed to the view function.
  • views.my_view: The view function that will handle the request when the URL pattern matches.
  • name='my_view_name': An optional name for the URL pattern, which can be used to generate URLs from within views or templates.

URL Dispatcher πŸ’‘

The URL dispatcher is the module that Django uses to match incoming requests to URL patterns. When a request comes in, the dispatcher iterates through all the registered URL patterns, and the first one that matches the request's URL is executed.

Django's URL Includes πŸ’‘

URL includes allow you to modularize your URL patterns. You can create separate files for different parts of your application, and Django will combine them to create the complete set of URL patterns for your project.

Here's an example of a URL include:

python
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ]

In this example, we're including the URL patterns from the 'blog' app, which we assume is a separate Django app.

View Functions πŸ’‘

View functions are Python functions that handle incoming requests. They are responsible for rendering templates, manipulating data, and returning HTTP responses.

Here's a simple example of a view function:

python
from django.http import HttpResponse def my_view(request): return HttpResponse("Hello, World!")

In this example, the view function simply returns a plain text response.

Practice Time 🎯

Now that you've learned the basics of Django routing, let's test your knowledge with a quiz:

Quick Quiz
Question 1 of 1

What does a URL pattern in Django do?

Advanced Routing Concepts πŸ’‘

In the next sections, we'll delve into more advanced routing concepts, such as:

  • Named Groups
  • Regular Expressions
  • URL Namespaces

Stay tuned for more exciting lessons on Django at CodeYourCraft! πŸš€

Note: For this tutorial, we'll be working with Django 3.2.


Here's a complete, working example of a Django project with routing:

python
# myproject/urls.py from django.urls import path from django.views.generic import ListView, DetailView from . import views urlpatterns = [ path('', ListView.as_view(queryset=views.Post.objects.all(), template_name='index.html')), path('<int:year>/<int:month>/<slug:slug>/', DetailView.as_view(queryset=views.Post.objects.all(), template_name='post_detail.html'), name='post_detail'), ]
python
# myproject/views.py from django.shortcuts import render from .models import Post def index(request): return render(request, 'index.html') class PostListView(ListView): model = Post class PostDetailView(DetailView): model = Post
python
# myproject/models.py from django.db import models class PostManager(models.Manager): def get_queryset(self): return super().get_queryset().order_by('-pub_date') class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='pub_date') pub_date = models.DateTimeField('date published') body = models.TextField() objects = PostManager() def __str__(self): return self.title
html
<!-- myproject/templates/index.html --> <h1>Latest Posts</h1> {% for post in object_list %} <h2>{{ post.title }}</h2> <p>{{ post.pub_date }}</p> <a href="{% url 'post_detail' post.year post.month post.slug %}">Read More</a> {% endfor %}
html
<!-- myproject/templates/post_detail.html --> <h1>{{ object.title }}</h1> <p>{{ object.body }}</p>