Django Web Application Framework for Python

  1. Install Python and Virtual Environment Setup

    Download and install the latest version of python from Python Website if not already done.

    Setting up virtual environment is not a must, but its is good to keep all your projects within a virtual environment. Here, we will proceed with a virtual environment.

    For that, go to the command prompt and cd to the folder where you are going to keep your project.
    Run command python -m venv FirstAppVENV to create a folder FirstAppVENV and a virtual environment for it.
    Activate the VE using command:

    For Windows:
    FirstAppVENV\Scripts\activate.bat
    For Linux, macOS:
    source FirstAppVENV /bin/activate

    After VE activation, from cmd type cd FirstAppVENV to navigate to the project folder.

  2. Install Django

    To install Django, run command pip install django

    Django installation may fail sometimes because of incompatibility with the latest python version. If so:

    Delete the already created virtual environment. Set it up again using the command.

    For Windows:
    py -3.9 -m venv FirstAppVENV
    For Linux, macOS:
    python3.9 -m venv FirstAppVENV

    Run pip freeze or pip3.9 freeze to check if Django installed successfully. Should give an output like this.

    asgiref==3.4.1
    Django==3.2.9
    pyodbc==4.0.32
    pytz==2021.3
    sqlparse==0.4.2
    
  3. Django Application Initial Setup

    A Django application is structured as a top level Django Project with zero or more Django Apps (modules) within it. Project will contain common codes specific to all sub apps.
    For our example, we will create a project within our virtual environment and an app inside it. We will explain the initial setup in multiple steps.

    Step 1: Create Django Project

    To create a project run:
    django-admin startproject FirstDjangoProject .

    Running the above command will create a project named FirstDjangoProject and a python file manage.py will get added. We are providing a ' .' after the project name to avoid an additional folder being created. If ' .' is not provided, new project and manage.py will be created within a folder FirstDjangoProject. See the folder structure below. Highlighted folders and files are related to VE, rest are created as part of Django project

    Django project folder structure

    Step 2: Create Django App

    Now on, we don't have to use django-admin in our commands. Use the below command to create our first app firstdjangoapp
    python manage.py startapp firstdjangoapp
    An app folder will get created with some new files and folders as highlighted in below image.

    Django app folder structure

    Step 3: Include app to our project

    For this, in settings.py, add our new app firstdjangoapp (case sensitive) to INSTALLED_APPS list as below.

    Django settings file
  4. Loading First Page

    This part explains how we are going to define the routes and where to place our html files. We are going to work on four files highlighted in below image. An html file and 2 urls.py file and views.py file
    Html files should be placed within a folder named templates. Create this folder in our firstdjangoapp app.

    Django loading first page

    Add a new html file firstpage.html, inside templates folder.
    We should have 2 urls.py, one inside, project folder and one inside app folder. If not available, create these. urls.py in project folder adds a reference to the app urls.py.
    In app urls.py we define the urlpatterns for this module.
    In views.py we define the web pages to render for each route. Code provided below.

    Run the app using command python manage.py runserver
    Copy the URL from command prompt and browse. We should get below output window.

    Django - First Page
  5. Django Project and App

    Steps on how to create a Django Project and app are explained in previous sections. Django Project can be considered as a top level folder which includes a collection of settings. Project holds the list of installed apps, database details, time-zone, language code, routing details, etc. Django App are modules where our web pages, static files, models and the actual python codes are located. A project can have zero or more app, but in most cases a project should have at least one app. Apps helps in splitting our entire project as sub modules.
    Details of some of the files that gets created automatically are listed below.

    File Name Description
    manage.py This file gets created at the time of creating the project. It is command line utility to do various tasks like running the project, create a new app, etc
    setting.py Project level file that holds details like list of installed apps, database details, time-zone, language code, etc
    Project - urls.py Hold routing patterns. Also includes reference to app level routing file
    App - urls.py Hold routing patterns specific to the app.
    models.py Declare app level model structures. Can have multiple models.
    forms.py Holds the form structure and required validations
    views.py This file is like a controller file that contains different methods that are called as per the routing and the actual logic
    templates This folder in app module holds all the html files
    static This folder in app module holds all the static files like css, images, javascripts, etc
  6. Django Models

    models.py file in the app folder can hold different models used within the app. Models can be imported to other files like:
    from firstdjangoapp.models import Country
    In below sample we are using a country model, which is used in views.py to show the data.

    Running the project should get below output window.

    Django models sample
  7. Django Forms

    forms.py file in the app folder can hold different form structures used within the app. Forms can be imported to other files like:
    from firstdjangoapp.forms import CountryForm
    Forms can be used to POST data from HTML files to python as in sample below.

    Run the project to see the output.

  8. Django - Common Field Types

    Field types are used while defining forms or models. Below are some of the most common field types. Different field types has many built-in attributes which can be used to define validations and other rules.

    Field Type Description
    CharField Hold strings of up to 255 characters
    TextField For larger strings
    IntegerField For whole numbers
    FloatField For decimal values
    DateField For dates
    EmailField For email data
    FileField Hold files
    ImageField Hold images
  9. Rendering the HTML page using Render method

    Use the render function to return an html page available in the template folder. Make sure that routes are defined in urls.py.

    from django.shortcuts import render
    
    def firstpage(request):
        return render(request, 'firstpage.html')
    
  10. Pass data from python back-end to web pages

    Suppose we have a variable declared in the python code and we want to show this in the web page. We can send this as a parameter of render function.

    from django.shortcuts import render
    
    def firstpage(request):
        testData = 'This is test data from python to html'
        return render(request, 'firstpage.html', {'td':testData})
    

    In the HTML, place this variable inside double curly braces as below.

    <label>{{td}}</label>
    

    To pass multiple variables, we can keep these as a model an pass it.

  11. Put Python code in web page

    Similar to Flask, Django also has the option to add python code directly along with the HTML content of a web page. Use the format {% #code here %} and place the code within.
    Add below sample codes to html and view.py file to see the output.

    from django.shortcuts import render
    def firstpage(request):
        planets = ['Mercury', 'Venus', 'Earth', 'Mars']
        return render(request, 'firstpage.html', {'planets':planets})
    
    <table class="table">
    <thead><tr><th scope="col">Planets</th></tr></thead>
    <tbody>
        {% for planet in planets %}
            <tr><td>{{ planet }}</td></tr>
        {% endfor %}
    </tbody>
    </table>
    
  12. HTTP Methods

    Django supports all the HTTP protocols listed below

    GETGet data from server
    POSTPost form data to server
    PUTMainly used to update data
    DELETEUsed to delete some data

    Using request.method, we can identify protocol. Use form.cleaned_data.get("field_name") to read data from controls. Sample below:

    Check cmd, when an HTTP action takes place to see the details.

    First page loaded
    [07/Dec/2021 16:42:59] "GET / HTTP/1.1" 200 1008
    First page loaded
    [07/Dec/2021 16:43:01] "GET / HTTP/1.1" 200 1008
    Value entered in textbox is 1 USA
    [07/Dec/2021 16:43:08] "POST / HTTP/1.1" 302 0
    Second page loaded
    
  13. Routing in Django

    Routes are declared in the urls.py file in app folder. In sample below, we have a default route for firstpage and another route for secondpage with an additional integer parameter.

    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.firstpage, name = 'firstpage'),
        path('secondpage/<int:id>', views.secondpage, name = 'secondpage')
    ]
    

    After this define how the routes are to be handled in views.py file. In secondpage method, we have an additional parameter id to get the value.

    from django.shortcuts import render
    
    def firstpage(request):
        return render(request, 'firstpage.html')
    def secondpage(request, id):
        print(id)
        return render(request, 'secondpage.html')
    

    Make sure to add the 2 html files in templates folder. Then run and browse http://127.0.0.1:8000/ to show firstpage and http://127.0.0.1:8000/secondpage/10 to show secondpage

  14. Redirect from one page to another

    Use redirect function as in sample below.

    from django.shortcuts import render, redirect
    def firstpage(request):
        print('First Page')
        return redirect('secondpage')
    def secondpage(request):
        print('Second Page')
        return render(request, 'secondpage.html')
    
  15. Static Files

    When we create a project, settings.py by default has a static file folder mentioned.
    STATIC_URL = '/static/'.
    Store static files like css and images in this folder.

Absolute Code Works - Python Topics