7. Dynamic routes

The goal will be to add an individual page for each article. To do this we will set up a dynamic route in Django.

For example:

  • http://localhost:8000/articles/1/ will show the article with id 1.
  • http://localhost:8000/articles/2/ will show the article with id 2.

The HTML will be the same for both pages, and even the view. The only difference will be the content of the article, which we will change dynamically depending on the id in the URL.

First edit the my_blog/views.py file and add the following code:

def article_detail(request, pk):
    article = Article.objects.get(pk=pk)
    return render(request, 'article_detail.html', {'article': article})

Create an article_detail.html file in the my_blog/templates folder with the following content:


<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="">
</head>
<body>
    <article>
    <h1></h1>
    <img src="" alt="">
    <p></p>
    </article>
</body>
</html>

And add the new view to the application URLs in my_blog/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.hello_world, name='hello_world'),
    path('articles/', views.article_list, name='article_list'),
    path('<int:pk>/', views.article_detail, name='article_detail'), # New
]

To access each of the articles, you need to add a link in the article_list.html template. We will replace the content of the article with the link to access the individual page:


<!DOCTYPE html>
<html>
<head>
    <title>Article list</title>
    <link rel="stylesheet" type="text/css" href="">
</head>
<body>
<h1>List of great women in the history of computing</h1>

    <article>
        <h2><a href=""></a></h2>
        <img src="" alt="">
        <p><a href="">Read more</a></p>
    </article>

</body>
</html>

Reload the page and you should see the links to the individual pages of each article. When you click on them, you should see the individual page.

Take a look at the URL. What do you see? What do you think the number means?

Here are a couple of challenges for you:

  • How could you change the URL so that instead of a number, it shows the article title?
  • How could you add a link to go back to the article list?

I recommend doing an internet search to find the solution. If you don't find anything, ask your mentor.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.