Django Tutorial for Beginners [Step by Step] – Part 5: Creating URL, View, and Template
Tutorial Goal: Create a URL, View, and Template to Render a Model
Welcome to Part 5 of this tutorial series! In this section, we will:
- Create a new view
- Query data from the database
- Render model data in an HTML template
This tutorial builds upon previous lessons, where you learned how to create a basic "Hello World" view. Now we will explore more complex views, introduce QuerySets, and demonstrate how to dynamically render model data in a Django template.
Prerequisites
- Knowledge of creating a basic Django project
- Knowledge of Django's Model-View-Template (MVT) architectural pattern
Refer to parts 1, 2, 3, and 4 of this tutorial series to get a basic understanding of the above.
Creating a View
In Part 1, we covered the basics of Django views—what they are and how they work. Now, let's create a more complex view that retrieves data from the database.
Step 1: Define a basic view
Open the views.py file in your song app and define an artist view:
def artist(request):
return HttpResponse("This is artist list")
This view simply returns an HTTP response with a static text message.
Step 2: Mapping the URL to the view
Next, update your urls.py file to map a URL to the artist view:
from django.contrib import admin
from django.urls import path
from . import views
from song.views import artist
urlpatterns = [
path('admin/', admin.site.urls),
path('say-hello/', views.hello_world),
path('', views.home),
path('artist',artist),
]
Now if you run the project and visit "http://127.0.0.1:8000/artist," you will see the text:
"This is the artist list."
But what happens in a situation where we have an artist list in the database and the user clicks on this URL? We want to be able to retrieve that data.
Step 3: Querying and displaying data from the database
Instead of returning plain text, let’s modify our view to retrieve artist data from the database.
Adding data via the Django admin panel
Before we display real data, let's add some artists manually using Django's admin panel:
- Log in to the admin panel (http://127.0.0.1:8000/admin).
- By default, Django only shows "Users" and "Groups."
- To manage artists, you need to tell Django to add our model (artist) section to its index page by registering the Artist model in admin.py.
- Open the admin.py module in the music app and add:
from django.contrib import admin
from .models import Artist, Song
admin.site.register(Artist)
admin.site.register(Song)
5. Refresh the admin panel. You should now see the Artists section.
After this, Django creates a music section with Artist model on the index page.
Now, the artist data is stored in the database.
Adding Data to the Model in Django Admin
In this section, we'll add artists to our model using the Django admin panel and display them in a template.
Step 1: Adding artists via Django admin
To manually insert artist data:
- Click on the add icon in that artist page on your admin panel
- Fill in the form with details such as name, birth year, and genre.
- As an example, add these four artists:
- Kurt Cobain
- Michael Jackson
- Freddie Mercury
- Roger Waters
Once added, the database will contain four artist records.
Step 2: Retrieving artists from the database
Next, we need to retrieve all objects from the database table so that we can render them within a template file and display the artist data.
Update your views.py file:
def artist(request):
artist_list = Artist.objects.all()
context = { 'artist_list':artist_list }
return render(request, 'artist.html', context)
Explanation:
- We use Artist.objects.all() to get all artist records.
- The retrieved data is stored in artist_list.
- We pass artist_list to the template using the context dictionary.
Step 3: Updating the template to display artists
Usually, we'd need to make some changes in the template file in order to show the specific fields of the object, like the name of the artist.
Open the artist.html and enter this code:
<!DOCTYPE html>
<html>
<body>
<h1>Artists</h1>
<ul>
{%for item in artist_list%}
{{ item.name }}
{%endfor%}
</ul>
</body>
</html>
How it works:
- The {% for artist in artist_list %} loop iterates through all artists.
- {{ item.name }} dynamically displays each artist’s name.
- The list is wrapped in <ul> tags for better structure.
Next:
Django Tutorial for Beginners [Step by Step] – Part 6: Django ORM.
If you wish to join a community of self-starters learning new skills and creating projects from scratch, join our Discord channel and share your passion.