Instagram logo to direct to CountMe tech ig profile page   LinkedIn logo that is directed to CountMe tech profile page

This tutorial will show you how to store inputted data into your Django Sqlite database as well as query the database to get information displayed on the user interface. We would utilise the Django framework, Python and Html in the process. The steps are:

 

Step 1: Create a Project Folder

In your terminal, first ensure your directory is where you wish to store your project folder. Then create your project folder:

% django-admin startproject pathway

Once you have created the ‘pathway’ project folder, make sure you are now working in your new directory:

% cd pathway

Next, create your new application folder (in this case ‘course’). This is where you will find the models.py and admin.py files which will be used to customise tables inside your database and display them on your admin UI.

% python3 manage.py startapp course

Django Folder structure

Figure 1: Django Folder structure

Add the created app’s name ‘course’ to the INSTALLED APPS list in your settings.py file by going to pathway > pathway > settings.py.

# Application definition
 
INSTALLED_APPS = [
   'course',                       # add course to INSTALLED APPS
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
  
]

 

Create and activate a virtual environment (venv) which will be used to run your project. 

% pip3 install virtualenv

% virtualenv venv

% source venv/bin/activate

 

Step 2: Create your Superuser account

First on your terminal, you need to install Django.

% pip3 install django

Migrate the default tables within django by using the below code.

% python3 manage.py migrate

Create a superuser account using the code below and input your username, email and password on request. You will receive a successful message on completion.

% python3 manage.py createsuperuser

After creating your superuser account, run your server using the code below and go to this link http://127.0.0.1:8000/ to see the image below.

% python3 manage.py runserver

Django launch

Figure 2: Django Launch

To gain access to the backend as the superuser, go to http://127.0.0.1:8000/admin you will observe the image below.

Django Admin database login

Figure 3: Django Admin database login

After inputting your superuser details, you should now be logged into your database. As mentioned earlier, the Groups and Users seen below are default tables created in Django.

Django database authentication

Figure 4: Django database authentication and authorization

 

Step 3: Populate your models.py file

Go to pathway > course > models.py

Add the following codes to your models.py file. 

from django.db import models
 
# Create your models here.
class Subject(models.Model):
   name = models.CharField(primary_key = True, max_length = 200, default='')
   grade = models.IntegerField(default=0)
   def __str__(self):
       return f"{self.name}"
   def __str__(self):
       return f"{self.grade}"

The Subject is a table to be created in your database while the name and grade are fields or columns on your table. The def __str__(self) is used to return the value of each field which would be used in the admin.py.

Note: ‘__’ is double underscore not one underscore. There are different types of fields like CharField, DateTimeField, ImageField, TextField, IntegerField, etc. In addition, setting your primary key as true for a field means the items in it must be unique.

 

Step 4: Populate your admin.py file

Go to pathway > course > admin.py

Add the following codes to your admin.py file.

from django.contrib import admin
from .models import Subject         # import Subject class from your models.py file
 
# Add your admin classes here.
class SubjectAdmin(admin.ModelAdmin):
   list_display = ('name', 'grade')
   list_filter = ('name', 'grade')
 
 
# Register your models here.
admin.site.register(Subject, SubjectAdmin)

The admin file is used to ensure the tables created in your models.py file are displayed on the UI. The list_display in the class SubjectAdmin is customised to show both fields created in the models.py file. On the other hand, list_filter is used to specify which field we would like to filter on the Subject table.

To actually visualise your Subject table, you will need to register it using the admin.site.register(Subject, SubjectAdmin).

 

Step 5: Apply migrations of new table

On your terminal, run the below codes to add the new table or any changes made to the sqlite database.

% python3 manage.py makemigrations

% python3 manage.py migrate

% python3 manage.py runserver

Go to http://127.0.0.1:8000/admin to see your newly created Subject table.

Django admin site administration

Figure 5: Django database admin model

 

Step 6: Populate your urls files

Create a urls.py file in your app folder (course), then open the file and populate it with the codes below. [pathway > course > urls.py]

from django.urls import path
from . import views
 
urlpatterns = [
   path('', views.index, name='index')
]

To register your newly created application urls.py file in the project, go to pathway > pathway > urls.py and copy the codes below.

from django.contrib import admin
from django.urls import include, path   # new import function
 
urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include('course.urls')),   # add course.urls in empty path string
]

Basically, once you click on your local host domain, you will immediately be directed to the index function in your views.py file.

 

Step 7: Create your HTML file

Create a ‘templates’ folder in your app ‘course’ folder and then create a folder named ‘course’ in your ‘templates’ folder as seen below. Finally create your index.html file in your new ‘course’ folder.

Django folder html structure

Figure 6: Django folder html structure

Go to pathway > course > templates > course > index.html

Populate the index.html file with the code below.

<!DOCTYPE html>    
<html lang="en">
   <head>
       <title>Coursework</title>
   </head>
   <body>
	<h1>Subjects and Grades</h1>
      
       <!-- Show Subject names and grades from database -->
       <h3>From Database</h3>
       <label>Subjects :</label>
       {{namesList}}
       <br>
       <label>Grades :</label>
       {{gradesList}}
       <br>
 
       <!-- Send Subject name and grade to database  -->
       <h3>Push to Database</h3>
       <!-- <form action="" method="POST"> -->
       <form action="{% url 'index' %}" method="post">
           <!-- CSRF security - generates a token to ensure no middle man accesses the form -->
           {% csrf_token %}
           <label for="subj">Choose a subject and its grade:</label>
           <!-- Subjects dropdown -->
           <select name="subj" id="subject" required>
               <option value="Mathematics"> Mathematics </option>
               <option value="English"> English </option>
               <option value="Science"> Science </option>
           </select>
           <!-- Grade dropdown -->
           <select name="grad" id="grad" required>
               <option value="95"> 95 </option>
               <option value="90"> 90 </option>
               <option value="100"> 100 </option>
           </select>
           <!-- Submit form button -->
           <br><br>
           <input type="submit" value="Send to Database">
           <br><br>
       </form>
   </body>
</html>

 

Go to http://127.0.0.1:8000 to see your html page on the frontend.

Html empty sql database

Figure 7: Html empty sql database

 

Step 8: Query database to retrieve data in views.py file

Go to pathway > course > views.py

Add the codes below.

from django.shortcuts import render
from .models import Subject
 
# Create your views here.
def index(request):
   ######################## Into Database ##############################
   # Check if the method is post
   if request.method == "POST":
       subject_name = request.POST.get('subj')        # get the subj selected by user from dropdownbox
       subject_grade = request.POST.get('grad')       # get the grad selected by user from dropdownbox
       # Create new instance of Subject table object to add data and save it
       subject = Subject()
       subject.name = subject_name
       subject.grade = subject_grade
       subject.save()
  
   ######################## From Database ##############################
   # Extract names from Subject table in database
   names = list(Subject.objects.all().values('name').order_by('name'))
   nameList = []   # to append value of the object property 'name'
   for name in names:
       nameList.append(name.get('name'))
   # Extract grades from Subject table in database
   grades = list(Subject.objects.all().values('grade').order_by('name'))
   gradeList = []   # to append value of the object property 'grade'
   for grade in grades:
       gradeList.append(grade.get('grade'))
 
   # Send namesList and gradesList variables to index.html file
   return render(request, 'course/index.html', {
       'namesList': nameList,
       'gradesList': gradeList
   })

The index function in the views.py will render a html file called ‘index’ which was created in the previous step.

 

Step 9: Outcome on Frontend UI and Admin UI

On the frontend, select your subject and grade and click the button to send the data to the database. In our case, at separate times, we added a grade of 95 and 100 for English and Mathematics respectively. The ‘From Database’ data will automatically update and display the data stored in your database as soon as the ‘Send to Database’ button is clicked.

Html populated sql database

Figure 8: Html populated sql database

Django backend populated sql database

Figure 9: Django backend populated sql database