Saturday, May 15, 2021

Python Django Setup Template

Here listed below are code snippets for creating a "PROJECT_NAME" Django Project with "APP_NAME" App.

1) Initial Set Up

  • mkdir My_Django_Folder
  • cd My_Django_Folder
  • pipenv install django
  • pipenv shell
  • django-admin startproject PROJECT_FOLDER_NAME .
  • python manage.py migrate
  • python manage.py createsuperuser
  • python manage.py startapp APP_FOLDER_NAME
  • python manage.py runserver

mkdir My_Django_Folder
cd My_Django_Folder
pipenv install django
pipenv shell
django-admin startproject PROJECT_FOLDER_NAME .

python manage.py migrate
python manage.py createsuperuser

python manage.py startapp APP_FOLDER_NAME
python manage.py runserver

Your project folder structure should look like this when you type 'tree' on the command prompt:-


It should also contain two files ("Pipfile" and "Pipfile.lock") that makes the virtual environment work properly.

If everything went successfully, you should get the welcome screen that congratulates you when you access the localhost with the given port number.





2) Add HTML/CSS/JS templates

At this point, you want to display a custom front-end the user instead of the default seen above. A front-end framework such as Bootstrap can be use, however, I will keep it simple by using a simple html/css/js files.

Recall from the step above, we create a django PROJECT and APP. Now, we need to edit some files within both folders like this:-
  • PROJECT folder: here we will edit these files - settings.py and urls.py
  • APP folder: here we will edit/create these files - urls.pyviews.py, and models.py. Note we could also add our templates folder here for the index.html but I prefer to create a root templates folder and point to it by updating the TEMPLATES list in PROJECT settings.py.

The following code snippets will add HTML/CSS/JS templates
  • mkdir templates
  • echo > templates/index.html (touch templates/index.html)
  • add your html code to the templates\index.html file
  • Update INSTALLED_APPS and TEMPLATES from PROJECT's settings.py
  • Update urls.py file from PROJECT's folder
  • Create a new urls.py file in app folder 'APP_FOLDER_NAME' and add view path
  • Update views.py file from the app folder 'APP_FOLDER_NAME' by defining the view added above. Since the name was called 'home', it most be the same in the views.py file.


If you do python manage.py runserver, this should load our html page from the templates folder as seen below:-


Notice that this is a very basic web page that didn't make use of a database, hence we didn't talk about the models.py file.

To add more pages for example, lets add contact page. We will create the contact.html file in the templates folder and update urls.py and views.py file in the app folder.



Note: If you don't want the .html extension to appear in the url like this "http://localhost:8000/contact.html", the edit urls.py file to remove the extension so that the path is like so... "http://localhost:8000/contact"



3) Adding Static file

In django, to use external CSS, JS, or Image files within HTML document you need to tell it how to get them by creating a root folder named "static" to house all the static files. The steps involved are as follow:-
  1. First thing is to update PROJECT's settings.py file by adding STATICFILES_DIRS


  2. Create a root folder named "static" and create another sub-folder with name of the app 'APP_FOLDER_NAME' 
  3. Add your static files there, for example I added an image 'buhari.jpg'
  4. Update the html file by first typing "{% load static %}" on the very first line. Then point to the file using this "{% static 'APP_FOLDER_NAME/buhari.jpg' %}"

The new home page should look like this...



This is the django way of doing things! In normal html, the inserted image tag will just look like this: <img src="APP_FOLDER_NAME/buhari.jpg " />

Likewise inserting a css or js file like this: <link rel="stylesheet" type="text/css" href="style.css"> in normal html will look like this: <link rel="stylesheet" type="text/css" href="{% static 'APP_FOLDER_NAME/style.css' %}"> in django way.

There are various delimeters, but the commonly used once are:-
  • {% %} - statements
  • {{ }} - expressions to print to the template output
  • {# #} - comments which are not included in the template output
  • # ## - line statements

Here is a nice tutorial on jinja template  by by zetcode.com which works similar to the django template.

Summary of file paths we edited or created:-
  • project\settings.py, project\urls.py
  • app\urls.py, app\views.py, and app\models.py
  • templates\index.html
  • app\models.py (...to be edited soon)
  • app\apps.py (...to be edited soon)

4) Add Database (Model)

Assuming our app requires a database, to create the database fields, we make use of the models.py file to define our models and django will do its magic behind the scene to create database table and fields ready to accept data into it.

Currently, this app doesn't use or need a database. However to demonstrate the use of models, lets assume we want the app to store the current time and date whenever the home page is accessed. That is whenever I reload this page "http://localhost:8000", the app records the current time, day and date in a database. That is all! As simple as it sounds, it is a good challenge to explore django models.

Since we have decided on what our database will store, those are our database fields.

By default, django comes with SQLite database which is a file-based database that requires no extract steps to setup. If you executed the line python manage.py migrate from the initial setup above, then you already created an SQLite database for the project named "db.sqlite3".


Here communicating with databases is done via Django Object-Relational Mapper (ORM) not SQL. With Django ORM, you just write normal python classes and django will translate it to database language.

Let open the models.py file to define of table in ORM style:-



Then we have to register the database table (VisitTime) in app's apps.py file be adding the lines below so we can see the table on the admin page like so...
from .models import VisitTime
admin.site.register(VisitTime)



Lastly, we will run the following lines of code;-
python manage.py makemigrations APP_FOLDER_NAME
python manage.py migrate


If you open the admin page "http://localhost:8000/admin" you should see the table we created with two field types (TimeField and DateTimeField).


There many other types of database fields such as "AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, DateField, DateTimeField, DecimalField, DurationField, EmailField, FileField, FilePathField, FloatField, ImageField, IntegerField, GenericIPAddressField, NullBooleanField, PositiveIntegerField, PositiveSmallIntegerField, SlugField, SmallAutoField, SmallIntegerField, TextField, TimeField, URLField, UUIDField, ManyToManyField, OneToOneField" however, our demo app is simply using those two similar datetime fields.

In this demo, I used two field types namely: TimeField and DateTimeField as seen below. 


The two fields are closely similar with jus the presence of date in the later. Lets keep only the later since it contains more details by commenting out the TimeField and run makemigrations and migrate.

Also, since we want the field auto populated when the page is load, lets add this parameter: auto_now_add=True to the DateTimeField  field. This will hide the form from the admin section, however you can click save the button to save the current date and time to the field.

Hit the save button couple of times, it will save the current datetime objects ('VisitTime object (1)', 'VisitTime object (2)', 'VisitTime object (3)', ... etc) as seen below:-

We can change the default generated string seen above to display the actual saved string by updating the with __str__() method as follow;-


The new listing should look like this...

Lets display the last visit date/time on the home page template as seen below...


To achieve this, we have to updated the following files (app/views.py and template/index.html).





Note: To update the current_date model field on page load, the following lines to the app/view.py file.
from django.utils import timezone
VisitTime.objects.create(current_date=timezone.now())



That is it.

My Rule of Thumb: Never use a django to create a Simple Basic Static website like the on above, instead use HTML/CSS/JS. Only use django to create Complex Dynamic App and Database driven website (a website that has a domain specific application purpose like file converter, engineering and sciences, ecommerce, social media etc.).

No comments:

Post a Comment