In this tutorial, we will learn how to create Django models. We are going to use Django 4.0. In the previous tutorial, we saw how to create your first project. We displayed hello world in our browser.
As a recap of what we saw in the previous lesson, let’s create a new project once more.
On your terminal, we can create a new directory for our project first. Let’s call new_project
$ cd Desktop
$ sudo mkdir new_project
$ cd new_project
When you are inside the new_project folder, now is the time to install Django. As a good practice, I always advise creating a requirements.txt file so that you can store all your installed applications. So to create a requirements.txt file, go to the terminal. Remember we are at the new_project directory.
$ sudo touch requirements.txt
Now that we have the requiremets.txt file, we can now use nano or vim to write into it. I am going to use vim text editor, you can use any you prefer.
sudo vi requirements.txt
Inside django inside this file.
django~=4.0
Create a Virtual Environment
Let’s begin by creating a virtual environment. Use the following code to accomplish that.
$ sudo python3 -m venv myvenv
Myvenv here is the name of our virtual environment.
Then we need to activate our virtual environment before we can begin our project.
source myvenv/bin/activate
Please make sure you see your terminal being prefixed by the name of your terminal like this.
(myvenv) [email protected]:~/Desktop/new_project$
Install Django
Let’s now install Django using the pip command inside the virtual environment. Remember the requirements.txt we created earlier, it’s now time we use it to install Django.
$ pip install -r requirements.txt
Collecting django
Using cached Django-4.0.4-py3-none-any.whl (8.0 MB)
Collecting asgiref<4,>=3.4.1
Using cached asgiref-3.5.2-py3-none-any.whl (22 kB)
Collecting sqlparse>=0.2.2
Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Installing collected packages: sqlparse, asgiref, django
Successfully installed asgiref-3.5.2 django-4.0.4 sqlparse-0.4.2
Now that we have installed Django successfully, we can proceed to create a project.
Start Django Project
To start a Django project, use the following command inside the virtual environment.
$ django-admin startproject main .
The name of our project is main and please don’t forget the period in the end. It shows that we are creating a project in the current directory.
After we have created the project, we can now move ahead and create Django app
python manage.py startapp products
The name of the app we are creating is products
Create Django views
A view function is a Python function that takes the web request and returns a web function. Let’s see with an example what we mean.
from django.shortcuts import render
from django.http import HttpResponse
def home_view(request):
return HttpResponse('Hello world')
Inside the products app, we need to create a urls.py file where the routing logic will occur. Add this file and proceed.
from django.urls import path
from . views import home_view
urlpatterns = [
path('', home_view, name='home'),
]
Go to main/urls.py file and create the following
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('products.urls')),
]
The next thing we need to do is to add our product name inside the settings.py file. Under installed apps, we need to add products app there like this.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products.apps.ProductsConfig',# add this file
]
To run our app use the following command inside the root of your django project. Here root is where you are having manage.py file.
$ python manage.py runserver
This is what we are going to see.
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 24, 2022 - 18:02:56
Django version 4.0.4, using settings 'main.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Don’t worry about unapplied migrations we will deal with that in a while. Open your browser and use this http://127.0.0.1:8000/ to open our development server.
Hurray! We have run our first Django program. If you are getting what you can see above, then we can proceed.
Creating Templates
From what we have created so far lies one big problem, here we are not in a position to render templates meaning we are not in a position to scale our project. What we ought to do is make use of templates. Here templates I mean make use of HTML files. Let’s see how we can implement this.
From the views.py file, we have what we have created above, I want us to delete return HttpResponse(‘ Hello world
’) and use return render(request, ‘html’)
from django.http import HttpResponse
from django.shortcuts import render
def home_view(request):
return render(request, 'products/index.html')# add this file
We need first to create a template file inside our products app. To do that, go to the products folder and create another folder and call it templates, make sure you spelled it correctly. Inside templates create an index.html file.
Before we can write anything inside the index.html file, we need first to move to the settings.py file and add our template path
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / 'templates' # add this file
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
First, let’s apply those unapplied migrations with the following command. This will populate our database.
$ python manage.py migrate
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Run python manage.py runserver again and open your browser.
We have arrived at the same thing but this time using template form.
In the next lesson, we are going to see how to perform CRUD operations using Django.