Arsalan Shahid

How to Define Django Models and Create Views – MovieStore Part 1

My dear reader, how are you? السلام عليكم

If four things are followed – having a great aim, acquiring knowledge, hard work, and perseverance – then anything can be achieved — A.P.J. Abdul Kalam

In this post, I explain how to configure Django with a practical example by creating simple internet movies storage application. I will show in detail how to configure the postgreSQL database, define Django models and make them work with Templates using builtin Django View functions.


Before we start, if you are in your infancy in using Django, I will suggest you go through following earlier posts:

  1. Inside Out of Django for Web Application Development (DirectMe)
  2. Getting Started with Django for Web Application Development (DirectMe)

Note: I will be using Ubuntu 18.04, Django 2.2.1 for this tutorial.

To start:

  1. Create an empty directory (I call it MyBlog)
  2. Create a Python virtual environment
  3. Install Django
  4. Install Python
  5. Create a movies App in the Django project (I name it moviesApp)
$ mkdir MyBlog
$ cd MyBlog
MyBlog$ virtualenv myenv
MyBlog$ source myenv/bin/activate
(myenv)MyBlog$ pip3 install django 
(myenv)MyBlog$ pip3 install python3
(myenv)MyBlog$ django-admin startproject movies
(myenv)MyBlog$ mv movies/ MyMovies # change the project name
(myenv)MyBlog$ cd MyMovies
(myenv)MyBlog/MyMovies$ python3 manage.py startapp moviesApp

We now list the created app in movies/settings.py in INSTALLED_APPS as shown below.

INSTALLED_APPS = [
    'moviesApp', # add this
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

We for this tutorial we will configure Django framework to work with PostgreSQL.

Goto movies/settings.py and change DATABASE from SQLlite3 to PostgreSQL as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mymdb',
        'USER': 'mymdb',
        'PASSWORD': 'development',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

While Django can create and run migrations for our Django apps, it will not create the database and database user for our Django project. To create the database and user, we have to connect to the server using an administrator’s account. Follow the tutorial to install it on ubuntu DirectMe. Once we’ve connected we can create the database and user by executing the following SQL:

CREATE DATABASE mymdb;
CREATE USER mymdb;
GRANT ALL ON DATABASE mymdb to "mymdb";
ALTER USER mymdb PASSWORD 'development';
ALTER USER mymdb CREATEDB;

We now define our application models. For that goto moviesApp/models.py

from django.db import models

class myMovie(models.Model):
    title = models.CharField(max_length=140)
    plot = models.TextField()
    year = models.PositiveIntegerField()

    def __str__(self):
        return '{} ({})'.format(
        self.title, self.year)

myMovie is derived from models.Model, which is also the base class for all Django models. If we look at the fields:

  1. title = models.CharField(max_length=140) This will become a varchar column
    with a length of 140.
  2. plot = models.TextField() This will become a text column in our database.
  3. year = models.PositiveIntegerField() This will become an integer column in our database. The value input would be validated first. It should be above 0.

Our model also has an __str__(self) method, which is a best practice that helps Django convert the model to a string.


We now need to do the following steps to register our myMovies model in Django admin. Goto moviesApp/admin.py and add the following:

from django.contrib import admin
from moviesApp.models import myMovie
admin.site.register(myMovie)

Make the database migrations using Django ORM.

(myenv)MyBlog/MyMovies$ python3 manage.py makemigrations
(myenv)MyBlog/MyMovies$ python3 manage.py migrate

After this, we need to create a superuser for our database.

(myenv)MyBlog/MyMovies$ python3 manage.py createsuperuser

Let us now define our views on moviesApp/views.py. For this example, we will use default ListViews provided by Django as follows:

from moviesApp.models import myMovie
class MovieList(ListView):
    model = myMovie

In the next post, we will continue with this basic app starting with the description on ListView. We will also see how to set URLs in Django and make the view interact with templates.

Signing off for today!

Exit mobile version