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.
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python
The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.
Buy the bookHelp me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.