How To Create Your First Basic Web Application Using Django
Do you want to build a web application on your own? Here’s a guide on how to do that using Python and Django Web Framework. Let’s build our first Django App. Django is a python web framework, follows MTV (Model-Template-View) pattern or simply creates a model that connects it to views, and views will fetch data from the model and render that data through the template. The Template holds an HTML page that renders our data. It can seem confusing at first. As we go through this article we will cover all these topics to have a better understanding.
Prerequisites
You should know Python to start the journey of this content.
I n this content we are going create our own database of some student with their marks, name, email and section. Add data of students in our database not manually but using Faker library(It generates fake data). And lastly we are going to show this information of the students through a table.
Getting Started
To start making our web app we need to first install Python and Django.
pip install django # Installing django
In this project, I am using Python — 3.7.7 and Django — 3.1.2 versions. So after installing Django let’s start our actual project. I am using Visual Studio Code as my text editor. You can use any other text editor to start it.
Project Setup
First, make a folder that holds all the files of this project. In the terminal, write:
mkdir Marks_App
Now we will create a virtual environment and activate it. The virtual environment will create an isolated environment for your project. So that the project can have its dependencies regardless of the dependencies of other projects.
>>> python -m venv ~/.virtualenvs/myenv>>> '~/.virtualenvs/myenv/Scripts/activate'
Activating the virtual environment we will start our project:
django-admin startproject marksproject
It will create your project folder and it will look like this:
The marksproject folder at the top is the project root. And the marksproject folder under this top folder is Django root. This Django root creates the project connection with Django. Now we have to move into our project folder:
cd marksproject
We are now in our project folder so we can create our app for our project.
django-admin startapp marksapp
Your app folder will look like this:
So, now in our project folder, we have two folders. — marksapp, marksproject.
In our marksproject folder, we have a settings.py file. We need to add the name of our app to its INSTALLED_APPS list.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'marksapp',
]
So up to this, our project is ready to run on the server:
python manage.py runserver
Starting the server we will get a default Django configuration page. Because still, we haven’t created any view to present on the page. Our project setup is now complete. We have created a project under which we have created our app folder. Now we can do whatever we want to do in our project.
Creating Models
Model is a structure where we store the data i.e. its fields and behaviors. To create a model we need to go into the models.py
file in the marksapp folder and create our model which will work for connecting with our database.
In the models.py file, we create a model name Student and add three fields: Name, Section, Email, Marks_obtained. But at first, we have to import models library from django.db
.
from django.db import models
# Create your models here.
class Student(models.Model):
Name = models.CharField(max_length=64)
Section = models.IntegerField()
Email = models.EmailField()
Marks_obtained = models.IntegerField()
Now we have to tell the database that we have made changes in our model. To do that the command below needs to be run in the console.
python manage.py makemigrations
makemigrations
create individual migration files based on the changes made in the models. Now to apply the changes to the database we need to migrate, migrate
informs the database about the changes made in the models.py
. In the terminal, enter:
python manage.py migrate
To operate our model from the database we use admin. And for this, we need to register our model in the admin.py file in the marksapp folder.
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Student)
Remember to import the models.py file in the admin.py file.
Log in to admin page
To login into our database, we need to create a superuser.
python manage.py createsuperuser
Give your username, email address, and password to create a superuser.
Now we can create, read, update, and delete in our database or simply do the CRUD operations in our database.
Generating Fake Data
Although you can generate data manually in a database, we are generating fake data in our database. It can be done by the Faker library. To do that first install the Faker library:
pip install Faker
Faker
is a package to generate fake data. The code written below is the code to generate fake data. I have created a population.py
file where I have written the code to generate fake data. And also we have to run that file in the console by entering python population.py
in the terminal to store those generated fake data in our database. Then repeat the migration process to check whether there are any changes to be applied in the database or not. After this, if you run your server the home page will still be the Django default page as we haven’t yet added any HTML code there. Go to /admin page and log in to your database, there you will get a Students Table where our data has been generated.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'marksproject.settings')
import django
django.setup()
from marksapp.models import Student # Importing the model created in models.py
from faker import Faker
import random
fake = Faker()
def populate(N=5):
for i in range(N):
fake_name = fake.name()
fake_sec = random.randint(1,12)
fake_marks = random.randint(0,100)
fake_emails = fake.email()
student_entry = Student.objects.get_or_create(Name=fake_name,Section=fake_sec, Email=fake_emails,Marks_obtained=fake_marks)
populate(10)
Views And Templates
Now we will create the views for our app. So go to the views.py
file in the marksapp folder and import our model. There we will create a python function called user where we will make a list of our students’ data, take the list as a value of a dictionary, and put the key of that dictionary as the context to be rendered.
from django.shortcuts import render
from django.http import HttpResponse
from .models import Student########################################################################### order_by is a SQL command where we get the data in order to any field# marks_list is the list where we store the data in order to the marks studentsget.# marks_dict is the dictionary where we store the list of marks as thevalue and the corresponding key is marks_info# This function will render the context we provided here marks_dict in theprovided HTML page###########################################################################def user(request):
marks_list = Student.objects.order_by('Marks_obtained')
marks_dict= {'marks_info': marks_list}
return render(request, 'index.html', context=marks_dict)
Now to render the views in the HTML page we store the HTML file in a Template folder and provide the folder’s path in the settings.py
file like:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = os.path.join(BASE_DIR,'Templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR],
'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',
],
},
},
]
Create an HTML page under the Templates folder where we will render our data.
In that HTML file, we will insert the key of that dictionary passed through the render function we created in the views.py file. It will render the data we needed, through a table. Don’t forgot to write the {% load static %}
code after the <!DOCTYPE html>
line. It loads all the staticfiles in the HTML code.
<!DOCTYPE html>{% load static %}<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Student Details</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"><link rel="stylesheet" href="{% static 'Style.css' %}" /></head><body>
<div class='container'>
<div class='jumbotron'>
<h1>Welcome To Index Page</h1>
</div>
<h2>Marks Table: </h2>
{% if marks_info %}<!-- inserting the key that we passed in the render function -->
<table class="center">
<thead>
<th>Name</th>
<th>Email</th>
<th>Section</th>
<th>Marks</th>
</thead>
{% for st in marks_info %}
<tr>
<td>{{ st.Name }}</td>
<td>{{ st.Email }}</td>
<td>{{ st.Section }}</td>
<td>{{ st.Marks_obtained }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>Table couldn't be accessed </p>
{% endif %}
</div>
</body>
I have added some CSS and Bootstrap to give a better look to the page. I have also added a home page to this project you can see that from my GitHub repository also if you get stuck at any stage while doing the project on your own you can check it out from there link .
Throughout this project, we have learned a lot of concepts like:
- Installing Django and activating the virtual environment
- Creating models and connecting the models to the database
- Generating fake data using Faker
- Connect the model to the view
- Connect view to the template
- Render the data to a web page through an HTML file.