Skip to content

Instantly share code, notes, and snippets.

@saifat29
Last active October 30, 2017 13:09
Show Gist options
  • Save saifat29/809f08d8b0f0aee1b97cbe7e84e54f52 to your computer and use it in GitHub Desktop.
Save saifat29/809f08d8b0f0aee1b97cbe7e84e54f52 to your computer and use it in GitHub Desktop.

Django Steps

Terminologies


The architectural design pattern of django is MVT (Model-View-Template)

Django Project: It is a collection of applications and configurations that when combined together will make up the full web application.

Django Application: It is created to perform a particular functionality for the entire web application. It can work individually and can be plugged into a project due to its modularity. e.g. registration app, comments app, etc. These Django Apps can then be plugged into other Django Projects, so you can reuse them.

Three Primary Steps for creating a complete Django Web Application -

  1. CREATE VIRTUAL ENVIRONMENT AND INSTALL REQUIRED PACKAGES (e.g django, etc. ) AND DEPENDENCIES
  2. CREATE NEW PROJECT
  3. CREATE APPLICATION(S) WITHIN THE ABOVE CREATED PROJECT TO MAKE THE COMPLETE DJANGO WEB APPLICATION.

Steps to setup Django:-


1) Create Virtual Env. $ python3 -m venv myDjangoEnv

2) Install required packages from PIP => e.g. django, etc. => When you install django it also installs a command line tool called “django-admin”, it lets you issue django commands from the command line .

3) Activate the Virtual Env. $ source myDjangoEnv/bin/activate

4) Create your project by issuing the following command: $ django-admin startproject [projectname] Your project file structure will look like the following:

[projectname]/
├── [projectname]/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└─── manage.py

project directory structure

After creating your project from step 4 following files are created - a) __init__.py - This is a blank Python script that due to its name special name let’s Python know that this directory can be treated as a package.
b) settings.py - This is where you will store all your project settings.
c) urls.py - This is where we will store all the URL patterns for the project. Basically, the different pages of the web app.
d) wigs.py - This Python script that acts as the Web Server Gateway Interface. It will later on help to deploy the web app to production.
e) manage.py - This is a Python script that will be use the most. It is used to issue django commands and is used for some other tasks.

Following examples are equivalent and can be used interchangeably to issue commands to django-

$ python manage.py <command> [options]
$ django-admin <command> [options]
$ python -m django <command> [options]

5) Run local server to check if everything till now is working alright by issuing the following command- $ python manage.py runserver (Note: The above runserver command is one of the many other commands that we issue to django as previously mentioned.)

You will see something like the following in your terminal-

$ Django version 1.11.4, using settings ‘first_project.settings'
  Starting development server at http://127.0.0.1:8000/

Visit the above mentioned URL to see the “Welcome to Django” page. (Note: If there is some error in the terminal or you don't see the welcome page don't try to debug as it will complicate things, delete the entire project and start from beginning by religiously following each step.)

6) Create your Django Application(APP) inside the above created project directory by issuing the following command- $ python manage.py startapp [app-name] Your project file structure will look like the following after creating your app:

[projectname]/
├── [projectname]/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├─── manage.py
│
└───[app-name]/
    ├── migrations/
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── models.py
    ├── tests.py
    └── views.py

The following is your app structure which is inside your project.

app directory structure

After creating your app inside your project from step 6, the following one directory and six files are created- a) __init__.py - This is a blank Python script that due to its name special name let’s Python know that this directory can be treated as a package. b) admin.py - You can register your models here which Django will then use them with its admin interface. d) models.py - Here you store the application’s data models. e) tests.py - Here you can store test functions to test your code. f) views.py - This is where you have functions that handles requests and return responses(views). g) migrations (directory) - This directory stores database specific information as it relates to the models.

7) Register the Django Application(APP) created in Step 6- Register your created app in the django project’s settings.py file by entering the app’s name in the INSTALLED APPS list.

Overall Working Of Django


working of django

(Note: Hereafter, the word “app” or “app directory” will be used to refer to the stand alone application created in Step 6 . And the word “project” or “project directory” will be used to refer to the project created in Step 4.)

Basic Django Web App:-


After completing of the above six steps, the actual application development starts here.

VIEW-

A view is a callable which takes a request(GET/POST request) and returns a response(view/Front End). This can be more than just a function, and Django provides some classes which can be used as views (by inheriting).

Step 1: Create a view (function) in your app’s view.py file to handle requests and return responses(view/front-end). (Note: Remember to import HTTP module.)

Example of a simple view :-

from django.http import HttpResponse

def index(request):
    return HttpResponse(“Hello, World!”)

Step 2: After creating your view create a url to return the above created view when request is made on the url. Make the following additions to the urls.py file in the project’s directory. Pass appropriate regular expression in the url() function that will match the expected url entered by user. Remember to import your previously created view.Example:-

Example:-

from your_app_name import views

urlpatterns = [
    url(r^$’, views.index, name=index’),
]

Step 3: Start your server and go to the url (localhost) to see the view returned.

URL MAPPING-

The previously shown method in the VIEW section is one way to map URLs to respective views, however since django apps are meant to be “pluggable (plug n play)” they should also be able to work independently (i.e. they should be portable). In the above URL mapping method the URLs are needed to be specified in the project’s urls.py file, this way the apps are dependent on the project for url mapping. The following method overcomes this problem by manually creating a urls.py file for each individual app, this way the app is modular (pluggable) and will work alongside other apps in a project.

Step 1: Manually create a urls.py file in the app’s directory.

Step 2: Import url module and your view.

Example:-

from django.conf.urls import url
from your_app_name import views	

urlpatterns = [
    url(r^$’, views.index, name=index’),
]

Step 3: Include the above created app’s URL mapping into the project’s urls.py, we do this by using the include() function to include the app’s urls.py into the project. (Note: Remember to import the include module.)

Example:-

from django.conf.urls import include
from first_app import views

urlpatterns = [
    url(r^my_app_name/’,include(‘my_app_name.urls’)),
]

(Note: We use Regular Expressions to match possible URLs)

This the best way to do url mapping.

TEMPLATES-

Templates are a key part in understanding how django really works and interacts with the web app. Templates are connected with MODELS to display data created dynamically (from database).

Templates have two parts -

  • The first will contain the static parts of an html page (parts that are always the same).
  • The second are the template tags, which have their own special syntax. This syntax allows to inject dynamic content that the app’s VIEWS will produce, affecting the final html.

Template tags are also knows as Django Template Variable.

Step 1: Create a templates directory in your project. And then a subdirectory with each app's name for each app.

[projectname]/
├── [projectname]/
│      ├── __init__.py
│      ├── settings.py
│      ├── urls.py
│      └── wsgi.py
├─── manage.py
│
├────[app-name]/
│    ├── migrations/
│    ├── __init__.py
│    ├── admin.py
│    ├── apps.py
│    ├── models.py
│    ├── tests.py
│    └── views.py
│	
└─── templates/
     ├── [app-name-1]
     ├── [app-name-2]
     ├── ...
     ├── ...
     └── [app-name-n]

Step 2: Now you need to let Django know of the templates by adding the template’s directory path in the settings.py, this is done by editing the DIR key inside the TEMPLATES dictionary in the settings.py file.

However the following issue arises- The directory path structure varies according to the OS being used, for example the templates directory looks like this in Linux/Mac - ../templates/app-name/

But in Windows it’ll look like this- ..\templates\app-name\

We actually require to “hard-code” the path in settings.py file, but “hard-coding” the path will make the Django Project to be non-transferrable or less portable as the path will be required to change to suit the operating system. To resolve this issue we make use of dynamically generated paths, this is achieved by using Python’s OS module to dynamically generate the correct file path strings, regardless of the OS.

In the settings.py file we have a variable BASE_DIR which stores the “base” directory path to the project. We create our own variable TEMPLATE_DIR and “join” the BASE_DIR with the templates directory.

Example-

TEMPLATE_DIR = os.path.join(BASE_DIR, “templates”) This will generate the appropriate path to the templates directory.

Now add this TEMPLATE_DIR as a value inside the list to the DIRS key in the TEMPLATES dictionary in the settings.py file. Example-

TEMPLATES = [
    {
        ‘DIRS’: [TEMPLATE_DIR,],
    }
]

Step 3: Inside your templates directory’s app directory add the HTML file.

└─── templates /
     ├── [app-name-1]
     │   └── index.html
     ├── ...
     ├── ...
     └── [app-name-n]

The HTML file will contain static (normal/usual) HTML along with Template Tags (Django’s Template variables).

Example:-

<!DOCTYPE html>
<html>
    <body>
	<h1>Hello, World!</h1>
	{{ insert_me }}
    </body>
</html>

The Django Template Tags are written inside double curly braces. The dynamically generated content is injected through these variable inside the HTML.

Step 4: We inject content into the template tags through the view. We use the render() function to achieve this.

Example:-

from django.shortcuts import render

def test(request):
    test_dict = {‘insert_me’:’I was injected’}
    return render(request, ‘app-name/index.html’, context=test_dict)

In the above example the ‘test_dict’ is a dictionary which stores data, data is stored in MODELS (database) which is extracted by the view and then injected. (For the sake of simplicity the data (here dictionary) is hardcoded in the view itself, in future we’ll use MODELS to achieve this).

When building a page that uses data, we pass the context variable to render() as well as the request object and the path to the template. The “render()” function renders the response based on the data provided by views.

The “render()” function takes three parameters - 1: The request object received to the view. 2: The template it can use to build the page. 3: The context which is a dictionary in which the keys are names we’ll use in the template to access the data and the values are the data we need to send to the template.

SERVING STATIC FILES IN Django-

Step 1: Create a directory called “static” in your project. Create separate directory inside the static directory for each of your apps. Now your project directory will be as follows

[projectname]/
├── [projectname]/
│   ├── ...
│   └── ...
│
├────[app-name]/
│    ├── ...
│    └── ...
│	
├─── templates/
│    ├── ...
│    └── ...
│
└─── static/
     ├── [app-name-1]
     │   ├── images/
     │   ├── css/
     │   └─── js/
     │
     └── [app-name-2]
         ├── images/
         ├── css/
         └─── js/

Step 2: Same as templates add this “static” directory path to the project’s settings.py file.

Example:-
STATIC_DIR = os.path.join(BASE_DIR, “static”)
STATICFILES_DIRS = [
    STATIC_DIR,
]

We create a list called “STATICFILES_DIRS” to add as many static files directories as required.

Step 3: We use Template Tags to load static contents inside our HTML.

Template tags are of two types - a) {{ }} - These are used for simple text injection. b) {% %} - These are used for more complex injections and logic. We add the following at the top of the HTML code only after the to load all the static files - {% load staticfiles %}

We then use the following to link the static file inside the code - Example:-

For image - <img src=“{% static “appname/path/to/image” %}” />

For CSS - <link href=“{% static “appname/path/to/css/file” %}” /> and so on...

MODELS-

We use Models to incorporate a database into a Django Project. Django comes equipped with SQLite, although Django can connect to a variety of databases.

To represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table.

Step 1: To create an actual Model, we use a class structure inside of the app’s models.py file. This class object will be a subclass of Django’s built-in class- django.db.models.Model Each attribute of the class represents a field, which is just like a column name with constrains in SQL

table table

For the above tables we create our Models as follows-

from django.db import models

class Topic(models.Model):
    top_name = models.CharField(max_length=264, unique=True)
    
    def __str__(self):
        return self.top_name


class Webpage(models.Model):
    top_name = models.ForeignKey(Topic)
    name = models.CharField(max_length=264)
    url = models.URLField()
    
    def __str__(self):
        return self.name

Step 2: After setting up the models we can now migrate the database.

Django does all the heavy lifting for us and creates the actual tables in the database according to the Models we created in our models.py file. We just need to issue the migrate command as follows to initiate this process- $ python manage.py migrate

Then register the changes to your app with the following command- $ python manage.py makemigrations app-name

Now migrate the database one more time- $ python manage.py migrate

Step 3: After finishing these steps we can interact with our models using two ways- i) Using the shell ii) Using the Django’s Admin Interface

(Note: Very basic insertion and retrieval is shown below, keep reading forward or visit the documentation site to go into details.) a) Using the shell -

  • We enter into the Python shell by issuing the following command- $ python manage.py shell (Note: You can enter the Python shell the usual way by just typing $ python, however you'll won't be able to interact with your Models since your project's settings.py file has to be configured accordingly.)
  • Import the Model/(s) you created in your models.py file as follows- >>> from app_name.models import ModelName
    Inserting Values
  • Insert values into the table by instantiating your model class as follows- (Note: Remember that a model class represents a database table, and an instance of that class represents a particular record in the database table.) >>> t = Your_Model(name="John Doe", gender="male")
  • Django won't perform the database operation until you explicitly call save()- >>> t.save()
    Retrieving
  • To retrieve all the entries from your model(table) issue the following command- >>> Your_Model.objects.all()
  • To view the results print the retrieved results- >>> print(Your_Model.objects.all())

b) Using the Django’s Admin Interface - For using the Django’s Admin Interface with the models we need to register them to our app’s admin.py file as follows-

from django.contrib import admin
from app_name.models import Model1, Model2

admin.site.register(Model1)
admin.site.register(Model2)

Then with the models and database created, we can use Django’s Admin Interface to interact with database.

This Admin Interface is one of the key features of Django.

In order to fully use the database and the Admin Interface, we’ll need to create a “superuser” We do this as follows- $ python manage.py createsuperuser

Now go Django's admin panel and login to view your database.

Step 4: Its better to populate the database with some test data for testing the application. Python’s Faker Library is used to achieve this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment