URLs in Django - potatoscript/django GitHub Wiki

When you visit a website, the URL in your browser's address bar corresponds to a specific page or resource on the site. In Django, URLs are used to map a web request (like a click on a link) to a view (a function that processes the request and returns a response).

Step 1: What Are URLs in Django?

In Django, URLs are how we link views to specific paths (web addresses) on our site. Each URL pattern is tied to a view, which will return the content of that URL when someone visits it.

Example:

  • When you visit http://127.0.0.1:8000/, Django can show you the homepage.
  • If you visit http://127.0.0.1:8000/about/, Django can show you the "About" page.

Step 2: Setting Up URL Patterns

In Django, URL patterns are defined in a special file called urls.py. When a request is made to the server, Django checks this file to see if the URL matches any patterns defined.

Let's see how to create a simple URL pattern:

  1. Create a urls.py file in your app directory. This file will store all the URL patterns specific to your app. If you created a blog app, the file might look like this:
blog/
โ””โ”€โ”€ urls.py  # Contains URL patterns for the blog app
  1. Define URL patterns in urls.py by mapping URLs to views:
# blog/urls.py
from django.urls import path
from . import views  # Import the views from the blog app

urlpatterns = [
    path('', views.post_list, name='post_list'),  # Default homepage for blog posts
    path('about/', views.about, name='about'),  # Another page, like About
]

Here:

  • path('', views.post_list, name='post_list'): This means that when someone visits the homepage (/), Django will call the post_list view.
  • path('about/', views.about, name='about'): This means when someone visits /about/, Django will call the about view.

Step 3: Linking to Views in views.py

Now we need to create the views that Django will call when users visit the URLs weโ€™ve defined.

  1. Create the views in views.py. This file will contain functions that handle each page request.
# blog/views.py
from django.shortcuts import render

def post_list(request):
    # This function will return all blog posts
    return render(request, 'blog/post_list.html')  # Render a template for posts

def about(request):
    # This function will render the About page
    return render(request, 'blog/about.html')  # Render a template for the About page

Each view function:

  • Takes a request as an argument.
  • Uses the render() function to return an HTML template.

Step 4: Adding URL Configuration to the Main Project

The main urls.py file (located in your project folder, e.g., mysite/urls.py) is where we include the URL configurations from each app.

You need to include the appโ€™s URLs into the main projectโ€™s urls.py file so that Django knows where to find the URL patterns for the blog app.

  1. Open mysite/urls.py.
  2. Add an include() function to bring in the blog appโ€™s URLs.
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include  # include is used to bring in URLs from apps

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),  # Include the blog app URLs here
]

Step 5: Creating Templates for the Views

Next, letโ€™s create HTML templates for the pages youโ€™re displaying with the views.

  1. Create a templates folder inside your blog app:
blog/
โ””โ”€โ”€ templates/
    โ””โ”€โ”€ blog/
        โ”œโ”€โ”€ post_list.html  # Template for displaying blog posts
        โ””โ”€โ”€ about.html      # Template for the About page
  1. Add some content to the templates:

post_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>Blog Posts</title>
</head>
<body>
    <h1>Welcome to the Blog!</h1>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about/">About</a></li>
    </ul>
    <h2>Blog Posts</h2>
    <p>Here is a list of blog posts...</p>
</body>
</html>

about.html:

<!DOCTYPE html>
<html>
<head>
    <title>About</title>
</head>
<body>
    <h1>About Us</h1>
    <p>Welcome to our website!</p>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about/">About</a></li>
    </ul>
</body>
</html>

Step 6: Testing Your URLs

Once youโ€™ve set up everything, start the server and test the URLs:

python manage.py runserver
  • Go to http://127.0.0.1:8000/ to see the home page of blog posts.
  • Go to http://127.0.0.1:8000/about/ to see the About page.

Step 7: Using Dynamic URLs

Django also allows you to make dynamic URLs. This means you can capture values from the URL and use them in your views.

For example, letโ€™s say we want to view a specific blog post by its ID.

  1. Modify the urls.py file to accept an ID in the URL:
# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('about/', views.about, name='about'),
    path('post/<int:id>/', views.post_detail, name='post_detail'),  # Dynamic URL with an ID
]
  1. Create the post_detail view:
# blog/views.py
from django.shortcuts import render

def post_list(request):
    return render(request, 'blog/post_list.html')

def about(request):
    return render(request, 'blog/about.html')

def post_detail(request, id):
    # In a real project, you'd fetch the post from the database using the id
    return render(request, 'blog/post_detail.html', {'id': id})
  1. Create the post_detail.html template:
<!DOCTYPE html>
<html>
<head>
    <title>Post Detail</title>
</head>
<body>
    <h1>Post ID: {{ id }}</h1>
    <p>Here is the detailed content for post {{ id }}...</p>
</body>
</html>

Now, if you visit http://127.0.0.1:8000/post/1/, Django will display the details for the post with ID 1.


โš ๏ธ **GitHub.com Fallback** โš ๏ธ