A Basic Django MVT application example is here.

1. Technologies & Prerequisites

    • Python 3.7, 3.8
    • Django 3.1
    • HTML 5

2. MVT Architecture

Django MVT Control Flow

The Model-View-Template (MVT) Architecture is a software design pattern for developing web applications.

  • The Model is an interface for maintaining and managing data in the database in proper tables.
  • The View interface executes the logic and interacts with the models.
  • The Templates help to render the information received as a response from the views based on the request on the browser for user interaction.

To know more about the MVT Architecture check this article.

3. Django MVT Basic Application Example

3.1 Virtualenv

The first step of beginning any python project is creating a virtual environment. Follow this tutorial to set up and activate a virtualenvand then install Django.

virtualenv env
source env/bin/activate
pip install Django

3.2 Setup Django Project

Start a Django project (here, project name:django_mvt) and create an app named home. Check this tutorial for more details.

django-admin startproject django_mvt
cd django_mvt/
python manage.py startapp home

01_create project

Add the name of the newly created app home to the INSTALLED_APPS list in settings.py.

django_mvt/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',
]

3.3 Design Model

A Model is basically a design for the database. Here, we will create a model for a simple database of books. This is specified in the models.py file in the newly created directory of the home app.

home/models.py
from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=250)
    author = models.CharField(max_length=250)

    def __str__(self):
        return self.title

3.4 Migrations

Django uses the sqlite3 database by default as specified in the settings. This can be changed as per requirements. Refer to Database Documentation for more details.

02_database

Now, run this command

python manage.py makemigrations home

You should get a similar output

03_makemigrations

The makemigrations command tells Django that some changes have been made to the specified model and to store the changes as a migration. A migration is how Django stores changes in the models and thus the database schema. Also, file is created home/migrations/0001_initial.py, where you can check the stored changes. You are not required to read this every time as it is just a reference to the changes that will be made, although you can edit them in case you want the manually make some changes.

You can try running this command to see the SQL query required to create the changes specified by the migrations to the database mentioned in the project settings.

python manage.py sqlmigrate home 0001
04_sqlmigrate

Also, one is not supposed to run this command every time. It is just to see SQL command for the migration file.

3.5 Migrate

Next, run the migrate command to actually make changes in the database ie. apply the migrations.

python manage.py migrate
05_migrate

The migrate command creates any necessary database tables for all the apps listed in the INSTALLED_APPS setting as per the database settings mentioned in the settings.py file. This all the unapplied migrations and synchronizes the changes in the database.

4. Entering Data

4.1 Django Shell

Django provides a free API using which one can use the interactive python shell and explore the Database API.

Invoke the python shell using this command:

python manage.py shell

Once inside the shell, we can read the data and enter/edit data as well.

# import the model class 
>>> from home.models import Book
>>> Book.objects.all()
<QuerySet []>

# create a new book
>>> b = Book(title="Atomic Habits", author="James Clear")
# save the object in the database
>>> b.save()

# the book is now available in the database
>>> Book.objects.all()
<QuerySet [<Book: Atomic Habits>]>

# it has an id and similarly we can access it other fields
>>> b.id
1
>>> b.title
'Atomic Habits'
>>> b.author
'James Clear'

# exit the shell using this command or use Ctrl+Z
>>> exit()
06_python shell

4.2 Django Admin

Django has its own inbuilt admin interface that helps the site managers, staff, clients to manage the data on the website. This is not intended to be used by the site visitors.

First, create a user who can log in to the admin site using this command. Then enter the desired username, email and password. For testing purposes, one can use a dummy mail too.

python manage.py createsuperuser
07_createsuperuser

Now, start the development server using the command.

python manage.py runserver

Then, navigate to the local domain of the django admin site on a web browser, ie. http://localhost:8000/admin/ and you should see the admin’s login screen.

08_admin_loginscreen

Enter the username and password entered while creating the superuser and then you should see the Django admin index page.

09_admin_index

But, we cannot see our Book data here.

For that, we need to register our Book objects with the admin interface. Edit the home/admin.py file as follows.

home/admin.py
from django.contrib import admin
from .models import Book

admin.site.register(Book)

On saving the file, the server with reload automatically and now we can see our Book data in the admin interface.

10_books_in_admin

You can click on the Book section and add new data using the admin panel.

11_add_data

   

 12_admin_book

5. View Data

5.1 Create Template

Next, create an HTML template to view the data as a site visitor. Create appropriate folders and add this to home/templates/home/index.html.
Refer to this article to know more about Django templates and this documentation for the syntax.

home/templates/home/index.html
<!DOCTYPE html>

<head>
    <title>Book Database</title>
</head>

<body>
    <h2>Book Database</h2>

    {% if books_list %}
    <ul>
        {% for book in books_list %}
        <li> <b> {{book.title}} </b> | {{book.author}} </li>
        {% endfor %}
    </ul>
    {% else %}
    <p>No books entered in the database. </p>
    {% endif %}
</body>

</html>

5.3 Views and URLs

Next, create a view in home/views.py to show the data in the database to the user.

home/views.py
from django.shortcuts import render
from .models import Book


def index(request):
    books_list = Book.objects.all()
    context = {'books_list': books_list}
    return render(request, 'home/index.html', context=context)

Here, we fetch all the objects and pass them to the context. The context is a dictionary mapping template variable names to Python objects.

Create a file home/urls.py with the following content.

home/urls.py
from . import views
from django.urls import path

urlpatterns = [
    path('', views.index),
]

Next, create a URL pattern for this app in the URL patterns for our project, ie. in the file django_mvt/urls.py.

django_mvt/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('home.urls')),
    path('admin/', admin.site.urls),
]

Now start the server using python manage.py runserver and we can see our data as per the format specified in the template.

13_web_output

6. References

Download Source from GIT:

Django MVT Example

Happy Learning 🙂

About the Author:

Ketan
An aspiring software engineer, exploring the dimension of Computers and Tech.

Leave A Comment