Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

Django Views

In the last tutorial we have created a base template and also we have seen a very simple view. In this tutorial, we create some pages for our application to show a list of books and also the details of each book. We also take a look at function-based views and class-based views.

Topics to be covered

We will cover the following topics in this lesson

  • Function Based Views
  • Lesson Challenge 1
  • Class Based Views
  • Lesson Challenge 2
  • Summary

Function Based Views

Function based views use function to retrieve data from the database and load templates using the render function. In the previous lessons, we already looked at how function based views work. In this section, we will use function based views to get data from the database and display it to the user in the browser.

Books Listing

Open the template /books/templates/books/list.html and update the code as follows

{% extends 'base.html' %}

{% block content %}
<div class="row">
    <table class="table">
    <thead>
        <tr>
        <th scope="col">Title</th>
        <th scope="col">Author</th>
        </tr>
    </thead>
    <tbody>
        {% for book in object_list %}
        <tr>
            <th scope="row"><a href="{% url 'books.show' pk=book.id %}">{{book.title}}</a></th>
            <td><a href="{% url 'authors.show' pk=book.author.id %}">{{book.author}}</a></td>
        </tr>
        {% endfor %}
    </tbody>
    </table>
</div>
{% endblock %}

HERE,

  • {% extends 'base.html' %} as we expect, it will extend the base template. We put the content of our list into the content block.
  • {% for book in object_list %} we also have passed an object_list to our template which is the queryset of our books. So, in our template, we have the query set. We can then loop into it using the for-loop.
  • {{book.id}} or {{book.title}} for each book we create a new table row. The book here is a book object, so we can put its fields in our template, for example: `{{book.id}} outputs the id of the book, {{book.title}} outputs the value of the book title.
  • {{book.author}} since it has a foreign-key relation with the author, we can also put its related author. Remember, we have used __str__ in our model? Now when we {{book.author}}, The author's name is put here directly.

In the previous lesson, we defined URL patterns and view functions that displayed simple templates. In this section, we will update the view functions so that we can pass data to our templates.

Open the file /books/views.py and update the index function as follows

def index(request):
	books = Book.objects.all()
	return render(request, 'books/list.html', {'object_list':books})

HERE,

  • def index(request): the function is called with a request parameter
  • books = Book.objects.all() books is a queryset. The query set gets all the books in the database. It is like a SELECT * FROM books.
  • return render(request, 'books-list.html', {'object_list':books}) we return a render. It tells Django to render a template file.

Start the built-in server then load the following URL into your web browser.

http://127.0.0.1:8000/books

You should be able to see the a list of books similar to the following

Django books app

The books displayed will depend on the data that you have created in your database.

Clicking on a book title should display the book details like in the following image

Book Details

Other Books Functions

The rest of the books functions are as follows

from django.shortcuts import render
from books.models import Book

def index(request):
    data = {
        'title':'Books Listing',
        'object_list': Book.objects.all(),
    }

    return render(request, 'books/list.html', data)


def show(request,pk):
    data = {
        'title':'Book Details',
        'object':Book.objects.get(id = pk)
    }

    return render(request, 'books/detail.html', data)


def edit(request,pk):
    data = {
        'title':'Edit Book',
    }

    return render(request, 'books/update.html', data)


def create(request):
    data = {
        'title':'Create Book',
    }

    return render(request, 'books/create.html', data)


def search(request):
    data = {
        'title':'Search Books',
    }

    return render(request, 'books/list.html', data)

The templates for the above functions have been included in the lesson downloadabl files.

Lesson Challenge 1

Update the functions for authors and categories like we did for books so that they all become functional and interact with the database.

By the time that you are done, you should be able to see something similar to the following.

Authors Listing

Clicking on an author should display the following results

Author Books

The categories page should display the following

Categories Listing

Class Based Views

We can do it easier. There are class-based views in Django which let us do the most recurrent works of view, easily. We have a ListView class that can query objects and renders the template. Not that they are classed not functions. So, in our views we change it:

from books.models import Book
from django.shortcuts import render
from django.http import JsonResponse
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView
from django.views.generic.edit import CreateView
from django.views.generic.detail import DetailView


class BooksListView(ListView):
    model = Book
    template_name = 'books/list.html'

    def get_context_data(self, *args, **kwargs):
        context = super(BooksListView, self).get_context_data(*args, **kwargs)
        context['title'] = 'Books Listing'
        return context


class BookCreateView(CreateView):
    pass


class BookDetailView(DetailView):
    model = Book
    template_name = 'books/detail.html'


    def get_context_data(self, *args, **kwargs):
        context = super(BookDetailView, self).get_context_data(*args, **kwargs)
        context['title'] = 'Book Details'
        return context


class BookUpdateView(UpdateView):
    pass

HERE,

  • model = Book the model variable defines the model that Django should run the query on.
  • template_name = 'books/list.html' The template_name is the name of the template to be rendered. objects_list is automatically called.
  • def get_context_data(self, *args, **kwargs): allows us to pass context data to our Class Views

and in our URLs, we change it to

from django.urls import path
from books.views import BooksListView, BookCreateView,BookDetailView, BookUpdateView, search

urlpatterns = [
    path('books', BooksListView.as_view(), name = 'books.index'),
    path('books/<int:pk>', BookDetailView.as_view(), name = 'books.show'),
    path('books/<int:pk>/edit', BookUpdateView.as_view(), name = 'books.edit'),
    path('books/create', BookCreateView.as_view(), name = 'books.create'),
]

HERE,

  • Note that since BooksListView is a class and URLs should call a function or method, we will call the as_view() method of the ListView.

Lesson Challenge 2

Update the functions for authors and categories to class based views just like we did in the above example when working with books application.

HINT:

We have defined categories as a field in book model but we have not defined a book field in our category model. So, if we are in a category template (object is a category), object.book.all return null. We should write it as object.book_set.all so Django searched the junction table.

Summary

Function based views use normal functions to query the database and load templates using the render method. They are a bit more flexible more requires more code compared to class based views. Class based views automate repetive tasks for us and the magic happens in the background. Just like the name suggest, class based functions are classes so we define them as classes. Url patterns should call functions and not methods so we call the as_view method on the View classes.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

Django Templates

Django Authentication

Leave A Reply