Create Model in Django - Tutorial for Beginners
Tags: django, webdev, python, appseed
Published: 2021-06-16 15:34:33

---
title: Create Model in Django - Tutorial for Beginners
published: true
description: A soft introduction in Django Models for beginners
tags: django, webdev, python, appseed
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/foh99vb5ayvznhxmruzs.jpg
canonical_url: https://docs.appseed.us/samples/django/create-model
---
Hello Coders, 

This article aims to help beginners to understand how to **[Create a Model in Django](https://docs.appseed.us/samples/django/create-model)** Framework by coding a new app from scratch and use mostly the terminal. The sample source code can be downloaded from Github (MIT License) and extended for hobby and commercial products. For newcomers, **Django** is a high-level Python Web framework built by experienced developers that encourages rapid development and clean, pragmatic design. 

> *Thanks for reading!* - Content provided by **[App Generator](https://appseed.us/)**.

--- 

- [Create Model in Django](https://github.com/app-generator/django-create-model) - source code (Github/MIT License)
- More [Django Samples](https://appseed.us/admin-dashboards/django) provided with authentication, basic modules

---

## Let's Code Django

> Check Python Version - recommended version is Python3

```bash
$ python --version
Python 3.8.4        <-- All good, we have a 3.x version
```

>  Create/activate a virtual environment - Unix-based system

```bash
$ virtualenv env
$ source env/bin/activate  
```
For Windows, the syntax is slightly different

```bash
$ virtualenv env
$ .\env\Scripts\activate
```

> Install Django

```bash
$ pip install django
```

>  Create a new Django Project

```bash
$ mkdir django-create-model
$ cd django-create-model
```

Inside the new directory, we will invoke `startproject` subcommand:

```bash
$ django-admin startproject config .
```

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

> Setup the database

```bash
$ python manage.py makemigrations
$ python manage.py migrate
```

> Start the app

```bash
$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/
```

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

![Django - Default Project Page.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pklhkp0fjhm5blmnabv4.png)
 
> Create a new Django application

```bash
$ python manage.py startapp sample
```

---

**Visualize the default SQL settings** - `config/settings.py`

```python
# File: config/settings.py (partial content)
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
...
```

---

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

```python
# File: sample/models.py

from django.db import models                       

class Book(models.Model):                                 # <- NEW
    title            = models.CharField(max_length=100)   # <- NEW 
    author           = models.CharField(max_length=100)   # <- NEW
    publication_date = models.DateField()                 # <- NEW 
```

---

**Update Project Configuration** to use the new model - The `sample` application must be added in the project configuration to `INSTALLED_APPS` section.

```python
# File: config/settings.py (partial content)
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sample'                        # <- NEW 
]
...
```

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

```bash
$ python manage.py check
System check identified no issues (0 silenced).  
```

---

> Generate the SQL code 

```bash
$ python manage.py makemigrations  # generate the SQL code
Migrations for 'sample':
  sample\migrations\0001_initial.py
    - Create model Book
```

> Apply changes on database

```bash
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sample, sessions
Running migrations:
  Applying sample.0001_initial... OK
```

---

**Use the model via CLI**

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

```bash
$ python manage.py shell
>>> 
>>> from sample.models import Book     # import the Book model in our context
>>> from django.utils import timezone  # used to provide the value for publication_date
>>>
>>> book1 = Book(title='The Adventures of Tom Sawyer', author='Mark Twain', publication_date=timezone.now() )
>>> book1.save()                       # save the new book
```

**List all books** (using the CLI)

```bash
$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: Book object (1)>]>
```

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

---

**Django Model** - add text representation of an object

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

```python
# File: sample/models.py

from django.db import models                       

class Book(models.Model): 
    title            = models.CharField(max_length=100) 
    author           = models.CharField(max_length=100)
    publication_date = models.DateField() 

    def __str__(self):       # <- NEW
        return self.title    # <- NEW
```

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

```python
$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: The Adventures of Tom Sawyer>]>
```

---

**Use the model via Admin Section**

Django comes with an `admin` section our-of-the box that allows us to manage with ease all models defined in 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 

```bash
$ python manage.py createsuperuser
sername (leave blank to use 'sm0ke'): admin
Email address: admin@appseed.us
Password: 
Password (again):
Superuser created successfully.
```

---

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

```python
# File: sample/admin.py

from django.contrib import admin

from .models import Book        # <- NEW

admin.site.register(Book)       # <- NEW
```

---

> 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.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmahhwx06g8qhzwnhbaj.png)

---

**Create Django Model - List Model Items**

![Create Django Model - List Model Items.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esatkcqz16d6jwkghwsw.png)
 
---

**Django Create Model - Edit Records**

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qc0q1iay0iknh2kfb7b2.png)

---

> **Thanks for reading!** Feel free to AMA in the comments section. 

--- 

## More Django Resources

- Read more about [Django](https://www.djangoproject.com/) (official docs)
- Start fast a new project using development-ready [Django Starters](https://appseed.us/admin-dashboards/django)