Django Create Model

Learn how to manage a new model in Django - free sample included.

This page explains how to create and USE a model in Django. All commands used to code the project and also the relevant updates are listed below. For newcomers, Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.

Resources

How to code this sample

This sample can be coded from scratch by following the steps below.

Check Python Version

$ python --version
Python 3.8.4 <-- All good

Create/activate a virtual environment - Unix-based system

$ # Virtualenv modules installation
$ virtualenv env
$ source env/bin/activate  

For Windows, the syntax is slightly different

$ # virtualenv env
$ # .\env\Scripts\activate

Install Django (the latest stable version)

Create a new Django Project

Inside the new directory, we will invoke startproject subcommand

Note: Take into account that . at the end of the command.

Setup the database

Start the app

At this point we should see the default Django page in the browser:

Django - Default Project Page.

Create a new Django app

Visualize the default SQL settings - config/settings.py

Define a new model Books in sample application. The below changes should be added to sample/models.py:

Tip - for a quick check over the latest changes we can run check subcommand.

Generate the SQL code (migrate the database).

Apply changes on the database

Use the model via CLI

Once the model is created we can use it via the Django shell:

List all books (using the CLI)

We can see our new book returned by the query. Let's improve the information that describes the object.

Django Model - add text representation of an object

To achieve this goal, we should define the __str__() method for the Book model

Let's restart the Django console and check the results:

Use the model via Admin Section

Django comes with an admin section out-of-the-box that allows us to manage with ease all models defined in the project. To manage the Book model in the administration console we need to create a superuser (aka the admin) and after register the Book model to be visible in the admin section.

Create the superuser

Register Book model to be visible in the admin section - Edit sample/admin.py as below:

Authenticate as admin - http://localhost:8000/admin/

At this point, we should see the Books model in the UI and able to execute CRUD operations.

Create Django Model - Admin Interface.
Create Django Model - List Model Items
Django Create Model - Edit Model Item

Resources

Last updated

Was this helpful?