You have successfully created objects for your model and its time to display them on the web browser.
For that, lets start with creating a base.html
file inside the templates
folder. The base.html
file will contain the basic template for your project, such as the loading of static files, navigation bar common to all pages etc. All the other templates will extend the base.html
and those templates will contain only the view specific code.
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Notes Application</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
Here, the base.html
file contains the bootstrap css and js links and placeholder for content.
Create another file named home.html
inside the templates folder, and extend it with the base.html
file and add a table to display the notes.
{% extends 'base.html' %}
{% block content %}
<div class="table-responsive my-3">
<table class="table table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>
Title
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
{% for note in notes %}
<tr>
<td>{{ note.title }}</td>
<td>{{ note.description }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
The home.html
file extends the base.html
and contains a for loop to display all the Notes that have been stored in the database.
The templates
for displaying the notes is ready, now you need to create a view for the template to display the notes and a corresponding route for it.
Open the views.py
file inside the notesapp folder and add the following code :
from django.shortcuts import render
from .models import *
# Create your views here.
def home(request):
notes = Note.objects.all() # Gets all the Note objects
context = {'notes':notes} # Pass the notes to the template
return render(request, 'home.html', context)
Here, a function named home
is created and the notes
data is passed to the template from it.
A route for the above view can be created as follows, open the notesapp/urls.py
file and edit the code as below :
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
After making these changes, when you start the server, you will be able to see the list of notes in the form of a table.
python manage.py runserver