Putting it together: SQL, Python and Web
We will cover a web application framework called Django, frameworks are effectively a library for a programming language that combines several other programming languages; allowing them to communicate to each other and perform complex operations, each framework will have its own syntax to learn.
To get the most out of this it is recommended you have read my previous posts introducing Python and SQL. Django is used to run many big sites, such as Instagram, Spotify, Pinterest, The Washington Post, The Onion and Mozilla.
Django
Django combines a stack of languages such as Python, SQL, HTML and more into an application - in our use-case we will create a website that uses a simple Python loop to iterate over a dictionary extracted from our SQL database and display it dynamically on our self-hosted webpage. It is much easier than it sounds and will only take 20-30 minutes of your time to setup.
Prerequisites
A code editor of your choice I highly recommend Microsoft’s Visual Studio code, its free, cross platform, has extensions to support just about any language and is very customisable. https://code.visualstudio.com/
Installation
Install Python over at https://www.python.org/downloads/ scroll down for specific instructions for your operating system
Python / Python3 pip install https://pip.pypa.io/en/stable/installation/ Pip installs packages (PIP) usually comes with Python and is a tool used to download and install software packages for Python; you can check if it’s installed with;
\Python3 for some systems
Python -m pip --versionDjango Django is easily installed using PIP with the command below, head to their official website for more detailed instruction at https://www.djangoproject.com/
pip install django
Once Django is installed we can create our new project with the below syntax;
django-admin startproject sitename directorynameAvoid names used by built-python or django components such as django or test. We are going to make a very simple site to be used by a fictional medical clinic, we will place this inside a folder on our computer
First create the folder on your system using
mkdir djangotutorialand then type
django-admin startproject mysite websiteDjango Hierarchy
Django will create a list of files in your directory;

init.py is an empty file that tells python to treat this directory like a python package.
asgi and wsgi are special configuration files used by Django to communicate with ASGI or WSGI compatible web servers to serve your project - we will not need to deal with these files today.
settings.py contains project settings - installs apps, plugin settings, middleware used and to modify database engines.
urls.py This is the table of contents for our site; it contains our URL declarations used to configure routes to different Django applications.
manage.py - special file that acts as a command line tool, allows user to make database migrations, run a python server, manage users via admin panel and more
Django applications
A Django app is what executes code or serves a webpage. An app could be a blog system, a database, an authentication system or a survey, Apps are standalone and plug and play. A project can contain multiple apps, an app can be in multiple projects.
Creating our first app
In the command line, head to your project directory (we have to be in the same directory as manage.py) and type the command;
python manage.py startapp clinicstartapp - creates new app
clinic - name of app
This creates a new directory for our app, the first step after creating our app is to link it to our project.
Go to settings.py in the main project directory (mysite) and scroll to installed applications and add our new app to the definitions, this will allow our Django project to view the code in the app.

While you’re editing settings.py, scroll further down and set the TIME_ZONE to your time zone. Storing data and coding with UTC is good practice, this will account for daylight saving time for applicable countries; and will resolve errors when their clocks are moved forward or back. You can display local time to the end user and still use UTC on the server side (This is best practice).
App hierachy

init - functions the same as in the main project, this filename tells python to treat this directory as a package.
admin.py - Allows registration of database models so we can view them in the admin panel.
apps.py - A place to store configuration specific to this app.
models.py - Used to manage models, a model in Django is a table in your database.
test.py - Used for automated test cases.
views.py - Where we will do most of our work - creates views or routes accessible on our website.
Setting up our clinic app
A view is a type of webpage, it usually has a specific function, this can be anything from a home page, comment action, index pages, redirect, image, error or many others. A website using Django is full of views and each view has its own task and function.
Head over to views.py to set this up.
Import the HttpResponse function from django

This function takes in a request object created by Django (HttpRequest - contains query parameters and the body of requests) and then defines and returns an appropriate response - this will be in the form of our webpage. It is up to you the writer to ensure each view instantiates, populates and returns a response.
Add the below code to return a string from the imported function.

You have now created the most basic view possible within Django but to be able to access it we need to map it to a URL.
Create a new file in the app; urls.py

Django will check this file and use it to place URL routes and connect them to our views.
add the following code to your clinic/urls.py file.

from django.urls import path - needed.
from . (current directory) import views - gives us access to functions from the views file that we just created.
We then create a list; urlpatterns.
Path - this will match a URL pattern to a specific path or view.
”“ - This empty string denotes the base URL of site.
views.index - We then call this function that we created in views.py; returning the HttpResponse and allowing us to view it.
name=’index’ - The name of the site
Now we need to connect the app URL to our main project - go to urls.py in our main project folder.
This contains all base routes for the entire project, Here we will create the URL that will link to our app.

’‘ - tells django to link the base URL to clinic.urls.
name=’clinic’ - defines a variable that we can use in other parts of our project to refer to this path.
Following the instructions in urls.py itself, be sure to import the include function from django.urls.
by including clinic.urls we pass on the handling of viewing the base URL to the URL list we created in doctors.
URLs by default will usually look something like website.com/projecturls/appurls. By specifying a blank string we don’t have to go to 2 subdomains to reach our homepage.
We also have flexibility to have different prefixes for different applications; eg. /admin has been created by Django by default for us to use.
Head back to your Python terminal and run the command
python manage.py runserver
Ignore any errors for now, these will be resolved with a later step.
Navigate to the webpage and and you can now see your page in action.

Press Ctrl+C or Ctrl+Break/Pause in your python terminal to stop running the server. This is good progress, but the page is bland.
Template page - boiler plate navbar
Using a template is best practice for modern web design, making it easier to have a consistent style across whole website without having to copy paste code, this greatly reduces double handling and errors.
Re-usable HTML gives the page a fast appearance as it is stored in the clients cache and only needs to be loaded once. Using Django we can have templates inherit from other templates - this can be powerful!
Create a new folder under doctors called templates and within this folder create a new html file called navbar.html.

For your own sanity it is best practice to store your templates in a folder within each app, creating subdirectories within the templates folder as needed. Storing all your templates in one folder will get messy and is not sustainable when working at scale.
Within a template there are blocks; these are what we will use to expand our templates in other pages.

blocks are overridable pieces of content, we can override this title block with other information in any page that inherits from this template.

copy the template below into your navbar.html file
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags for character set and responsive viewport -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS from CDN (Content Delivery Network) -->
<!-- Note: In production, it's better to download and host these files yourself -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Title block - Django will inject content here -->
<title>
{% block Title %}
{% endblock %}
</title>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<!-- Brand/logo link - points to home page -->
<a class="navbar-brand" href="{% url 'index' %}">Medical Clinic</a>
<!-- Hamburger menu button for mobile devices -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navigation links - will collapse on small screens -->
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto"> <!-- ml-auto pushes items to the right -->
<li class="nav-item">
<!-- Note: Replace index href with Django URL tags when routes are defined for these pages -->
<a class="nav-link" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">Doctors</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">Contact</a>
</li>
</ul>
</div>
</nav>
<!-- Main content block - Django will inject content here -->
{% block content %}
{% endblock %}
<!-- JavaScript libraries required for Bootstrap -->
<!-- Loaded at bottom of page for better performance -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
Create a new folder in your templates folder called clinic and then create a home.html file

and type the following code;

Keep in mind Django will choose the first template whose name it finds matches, if you have a template with the same name but in a different application, Django will be unable to distinguish them.
This makes it very important to use sub-folders when creating new templates such as clinic/home.html.
Head to views in our app and change the below code to render our new home.html webpage instead of returning a string response.

In your python terminal run the server once more using python manage.py runserver (ignoring errors once again); head to the default URL and you will now see a slightly fancier homepage displayed.

Setting up our database
Head to models.py; here we will create our database model for use. Django provides us with a object relational mapping (ORM) allowing us to write python code to create different database models and have those models conform to database schema such as SQL.
Add the below to your Models.py file.

We have created a Doctor which is a model, this model has 3 different fields written as Python attributes, these are set as characters with a limit set out as per the max_length attribute.
We need to register this model through the admin panel then convert the model to a database.
Head over to admin.py; by referencing the model here and registering to the admin panel we can view and edit via said panel.

As we create models we will need do what is called a migration - this is pre-written code that will go and create the corresponding code in a language (such as SQL or MongoDB) effectively converting it into a database for our use.
Any time you make a change to your database model you need to make a migration, this allows Django to update your database while ensuring the data itself is not compromised while making changes to the schema. Do this by typing
python manage.py makemigrations into your terminal, and then apply the migration by typing
python manage.py migratethis applies the migration and updates the database for you.
To summarize you need to make your migration and then apply it - do this every time you make a change to your database!
Migrations let you change your models over time as you develop your project, without needing to delete your database or tables and make new ones - You can upgrade and change your database live without losing data!
Viewing our database
Create a new html template in your templates folder to display your data.

{% extends "navbar.html" %}
{% block Title %}
Doctors
{% endblock %}
{% block content %}
<h1>Our Doctors</h1>
{% for x in Doctors %}
<h2> {{ x.name }}</h2>
<p><b> {{ x.qualification }} </b></p>
<p>{{ x.aboutme }}</p>
{% endfor %}
{% endblock %}
We have a loop; for each doctor in our database (Doctors) we use it to render different text items via HTML for each entry; this is a variable we can pass into this template.
We can use dot notation to access an attribute of this variable (doctor.name) which is treated as a python dictionary. Variables in django are defined with double curly braces {{ variable.attribute }}
In our views.py add
from .models import Doctorto reference the database.
Then we will add a reference to doctors.html by

We declare items in the function as a variable that we can pass to the request; it is set it equal to our database. we return that variable as {“Doctors”: data}.
Our earlier created html template now has access to this database.
So that we can access this webpage we need to add a new path to urls.py

Head into your navbar.html template and amend the highlighted code now that we have a URL for our doctors page;

You can now view this via your web browser; you will notice there is no data to show, we will now create some data via the admin panel.
Admin panel
In terminal type
python manage.py createsuperuserfollow the prompts, you can skip email. After creating a super user run the server and head to /admin on your webserver.
login with the credentials you just created; you will see your database models, click add and create some data!
head back to /doctors and you will see the items are now rendered. these are now present in your SQL database which is running on your PC and has persistence.
In a real world scenario you can add user accounts for staff or clients so that they can perform CRUD actions on your SQL database, such as a medical clinic practice manager entering in the details of a new doctor.
This has just been the very basics to give you a simple understanding of how some websites work!
Check out the below for more guided tutorials that go into more detail!
- Django Official Documentation - writing your first app https://docs.djangoproject.com/en/5.1/intro/tutorial01/
- W3 schools - https://www.w3schools.com/django/index.php