10- Display Database Records on a Template

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.


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})



 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 %}
{% endblock title %}

{% block content %}
    <div class="container">
        <table class="table table-bordered">
            <thead class="thead-dark">
                <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>
                {% for m in movies%}
                {%endfor block%}
{% 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.