5. Dynamic listing

The goal will be to display the articles you added in the admin panel on the main page.

Edit the my_blog/views.py file and replace all the content with the following code:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Article # New

def hello_world(request):
    return HttpResponse('Hello, world!')

def article_list(request): # New
    articles = Article.objects.all() # New
    return render(request, 'article_list.html', {'articles': articles}) # New

Create an article_list.html file in the my_blog/templates/ folder (you will need to create it) with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Article list</title>
</head>
<body>
<h1>List of great women in the history of computing</h1>

    <article>
        <h2></h2>
        <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.article_list, name='article_list'),
        path('articles/', views.article_list, name='article_list'), # New
]

Go to http://localhost:8000/articles/ and you should see the articles you added in the admin panel.

Wait a moment... why aren't the images showing? In the next section we will fix it.

Displaying images

All the content we upload to the database will be stored in the media folder. For Django to be able to serve these files, we need to add the routes to my_app/urls.py:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings # New
from django.conf.urls.static import static # New

urlpatterns = [
    path('', include('my_blog.urls')),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # New

Now you should see the images on the page.

The look is not very pretty, let's add a bit of CSS!

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.