How to use Django Python

What is Django?

Django is a Web framework (A software framework designed to support the development of web application) based on the Python language.

Some web applications built using Django that you might recognise include: Instagram, Mozilla and PBS of many

External Help

The Django documentation is a go-to place for most help and support that you will need:

https://docs.djangoproject.com/en/3.0/

Django Girls A concise guided walk through which shows all the features of django:

https://tutorial.djangogirls.org/en/

r/Django community of Django developers on Reddit

https://www.reddit.com/r/django/

r/learnDjango ask Django related questions and support other Django developers

https://www.reddit.com/r/learndjango/

Up and Running

First Time

Create a folder that you are going to work in - in this folder we are going to install three folders; A virtual environment, An installation of Django and the application we are work on

Open the folder in terminal

Make sure you have git installed (type git into command prompt to check)

Git clone Django

git clone https://github.com/django/django.git

Create a virtual environment

python -m venv .virtualenvs/djangodev

Activate your virtual environment

.virtualenvs\djangodev\Scripts\activate.bat

Install Django in virtual environment

python -m pip install -e django

Create the application (change "ProjectName" to the name of the application you want to create)

django-admin startproject "ProjectName"

You have now created a Django project.

You now need to create a application in our project, we will call it "main" (You can call it a different name if you want) later we will create another application alongside for logging in.

python manage.py startapp main

To get the site up and running you need to open your chosen "ProjectName" folder (This is the folder with manage.py) then run the following command:

python manage.py runserver

You should see the following in the terminal

System check identified no issues (0 silenced).
    Date - Time
    Django version, using settings 'mysite.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CTRL-BREAK.
    

In a browser type in the following url http://127.0.0.1:8000/

This will open the following page:

You are now ready to start building your web app

Returning to work on your Django project

This is for Windows OS

On returning to work on your web app make sure you:

Activate your virtual environment

Open the folder in the terminal that contains .virtualenvs, django and your chosen "ProjectName"

Enter the following

.virtualenvs\djangodev\Scripts\activate.bat

Run the server

Open your chosen "ProjectName"

folder (The one that has manage.py) in the terminal then run the following command

python manage.py runserver

Setting up the Settings

Inside of your chosen "ProjectName" there is another folder with the same name - Go into that folder

There should be a file called settings.py - open it

Change the following

Language Code

locate where it says LANGUAGE_CODE = '...' then change it accordingly

Time Zone

locate where it says TIME_ZONE = '...' then change it accordingly

Attach your App

locate where it says INSTALLED_APPS = [ ... ] inside of the list and add your application in this case 'main' like so:

'main.apps.MainConfig',

The installed apps should like this: (note the comma)

INSTALLED_APPS = [
    'main.apps.MainConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Dealing with the Database Part 1

Useful documentation when dealing with Django databases: https://docs.djangoproject.com/en/dev/ref/settings/#databases

In the settings file navigate to DATABASES = {...}

You can change the database, the default is sqlite3

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Writing HTML and CSS Prerequisite

Create two folders inside your App folder in this case 'main'

One called templates

One called static

Inside the templates folder create a folder with the same name as your app in this case 'main' - This folder will contain all your HTML files

Inside the static folder create a folder with the same name as your app in this case 'main' - This folder will contain all your CSS and JS files

Presenting HTML and CSS files - views.py Part 1

Head over to the 'views.py' file in the app folder which is located in the ProjectName folder in our case the main folder in the ProjectName folder

import render from django.shortcuts

from django.shortcuts import render

Create a function lets call it 'home'- this will be used to render our first page

def home(response):
    return render(response, "main/index.html", {})

We need to take in the input 'response' as this is required in the render function

We output a render of our html page

Presenting HTML and CSS files - urls.py Part 2

Open 'urls.py' file in the app folder which is located in the ProjectName folder in our case the main folder in the ProjectName folder

import your views file

from django.urls import path
    from django.conf.urls import url

    from . import views
    

In the urlpatterns list create a path function - this will take three inputs

  • The url pattern that will be typed into the browser - in our case we will have 'welcome/'
  • The location of the function to be used when that page loads - in our case views.home
  • The name that will be used to reference this url in the templates - in our case we will have name='hello'
urlpatterns = [
    path('welcome/', views.home, name="hello"),
]

Remember the comma at the end of the list

Presenting HTML and CSS files - index.html Part 3

Open the templates folder you created to store html files in the prerequisite section

create a html file - in our case index.html

Open index.html here will be all your html content

We will use the bootstrap starter template to get started

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>

Presenting HTML and CSS files - run server Part 4

If you don't have the server already running run the server using the command:

python manage.py runserver

Go to a web browser then type in:

http://127.0.0.1:8000/welcome

You should see a page that says Hello, world!

Writing a 'base.html' - makes html templates more efficient

When you are writing html files certain elements will be repeated on every page, for me it usually is:

  • Meta
  • Stylesheet
  • Title
  • Navigation bar
  • Body
  • Footer

Create a html file with all of these sections.

The parts that will change on each page use 'block name ' and 'endblock name'

For example the title - We can rewrite it like so:

<title>{% block title %} {% endblock %} | mysite</title>

My base.html looks like this:

{% load static %}

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'main/style.css' %}">

<!-- Title -->
    <title>{% block title %} {% endblock title%} | Mysite</title>
  </head>

<!-- Navbar -->
<nav class="navbar navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
</nav>

<!-- Body -->
  <body>
    {% block content %}

{% endblock content %}

    <!-- Optional JavaScript -->
    {% block JavaScript %}

{% endblock JavaScript %}

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<!-- Footer -->
<footer> Footer </footer>
  </body>
</html>

Loading static files including CSS and JavaScript

There are two parts to loading static files

have load static at the top like so:

{% load static %}

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

Next attach the file by using the name static followed by the file location of css/javascript in the static folder like so {% static 'appname/style.css' %}

<link rel="stylesheet" type="text/css" href="{% static 'main/style.css' %}">

Making use of 'base.html'

Create another HTML page or edit index.html(make sure index.html is empty)

You need to "import" the base.html file - At the top of the new HTML page have the following line

{% extends 'appname/base.html' %}

This will make sure all tags and elements in base.html will be in the your new HTML file

Next we need to fill our blocks so type in:

{% block title %}Home {% endblock title%}

{% block content %}<p>This is the main body </p>{% endblock content %}

We don't have any javascript so we can leave that

Your page should look something like this:

{% extends 'main/base.html' %}
{% block title %} Home {% endblock title %}

{% block content %}
<h1>Home Page</h1>

<p>This is the main body</p>

{% endblock content %}

Run the server and open the page

Right click to see view page source - this will show you how the base template has been used

Passing variables from views.py to your template

Open views.py

Earlier we created a function

def home(response):
return render(response, "main/index.html", {})

The dictionary {} in the render function allows us to pass variable data to our html page

There are three types of variable data I have passed:

Basic strings:

def home(response):
    variable = "HELP WITH PYTHON "
    return render(response, "main/index.html", {"information":variable})

Passing Lists:

def home(response):
    lst = ["HELP","WITH","PYTHON"]
    return render(response, "main/index.html", {"information":lst})

Passing Dictionaries

def home(response):
    dictionary = {"score":50, "highScore":100}
    return render(response, "main/index.html", {"information":dictionary})

You can pass multiple values to the template

Extend your dictionary like so:

def home(response):
    variable = "HELP WITH PYTHON "
    lst = ["HELP","WITH","PYTHON"]
    dictionary = {"score":50, "highScore":100}
    return render(response, "main/index.html", {
        "variable":variable,
        "list":lst,
        "dict":dictionary
    })

Using the values passed in the template

In views.py we are sending the dictionary (the one found in the render function)- make a note of the keys as this is what we will be calling in the HTML template

The key in this information that we are planning to use is "information"

Open your index.html page/the page you are rendering (the file in the return -> render function).

To use what is stored in information do the following {% information %}

{% extends 'main/base.html' %}
{% block title %} Home {% endblock title %}

{% block content %}
<h1>{% information %}</h1>

<p>This is the main body</p>

{% endblock content %}

9.30 Fri 8.30 Mon 8.30 Tue European Work time directive SSL RENEWAL aae97130 07861647272

Running Django, especially Django querysets in jupyter notebooks might be useful if you want to analyze/plot the data that is in your database. Also, sometimes it’s hard to execute big querysets in CLI using Django’s interactive shell. In this article, we will see how to connect Django’s shell with the Jupyter Notebook and get the advantage of executing querysets in notebook cells.

Source:https://davit.tech/django-jupyter-notebook/

You will find the most commonly used Django QuerySet examples with SQL codes.

Source:https://davit.tech/django-queryset-examples/