Before fetching database data into the template, I will change the navbar's background color to a custom color by just modifying the first line of my navbar.
<!--Navbar Starts Here-->
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #86aac4;">
<!--Login and Register Buttons-->
<a class="btn btn-outline-light" href="#">Login</a>
<a class="btn btn-outline-light" href="#">Register</a>
<!--Menu Items' Text as White -->
<a class="navbar-brand text-white" href="#">Movies</a>
<a class="nav-link active text-white" aria-current="page" href="#">Home</a>
<a class="nav-link active text-white" href="#">MoviesApp</a>
This is how navbar looks now.
Fetching Database Records into a Table:
I am going to change my existing moviesapp view. urls.py has already has an entry and we already created a template named moviesapp.html in prevous articles. I will just modify existing view and template.
Instead of a Hello message, it will display some database records.
views.py
The query fetches all the movies.
from django.shortcuts import render
from django.http import HttpResponse
from moviesapp.models import MyCustomUser, Movie, UserComment, Watched, Actor
# Create your views here.
def moviesapp(request):
movies = Movie.objects.all()
return render(request, 'moviesapp.html', {'movies': movies})
moviesapp.html
myquery returns a list of objects. I can use a FOR loop to iterate through that list and display their corresponding values.
{% extends 'base.html' %}
{% block title %}
<title>Hello</title>
{% endblock title %}
{% block content %}
{{movies}}
<div class="container">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Gender</th>
<th scope="col">Description</th>
<th scope="col">MovieFile</th>
<th scope="col">Photo</th>
<th scope="col">Resolution</th>
</tr>
</thead>
<tbody>
{% for m in movies%}
<tr>
<td>{{m.title}}</td>
<td>{{m.gender}}</td>
<td>{{m.description}}</td>
<td>{{m.moviefile}}</td>
<td>{{m.photo}}</td>
<td>{{m.resolution}}</td>
</tr>
{%endfor block%}
</tbody>
</table>
</div>
{% endblock content %}
Before fetching data into the table, I printed myquery's result (QuerySet) to show how objects are fetched in a list and we can iterate thru them by using a for loop.