Getting Started with Django – DEVELOPPARADISE
09/05/2018

Getting Started with Django


Getting Started with Django

Django is an open source web framework that enables you to build clean and feature rich Web Applications with minimal effort needed and in no time. It is written in Python; a general purpose language; but is well suited for developing Web Applications. Django loosely follows a model-view-controller (MVC) design pattern, which greatly helps in building clean and maintainable web applications. For the introduction purposes, you’ll read the following:

  • The MVC pattern in web development.
  • Why Python.
  • Why  Django.

The MVC pattern in web development

Web development was a tedious task involving the use of CGI for interfacing external program with the web server. It was just not difficult but also required a separate copy of the program to be launched for each request. Quite overwhelming isn’t it?

A few years ago, Model-View-Controller came for web based applications. It separates data (model), user interface (view), and data handling logic (controller), so that, one can be changed without affecting the other; benefiting the designers and developers to work on the same application without affecting and worrying about each other’s job. SWEET.

Why Python?

Python is a general purpose programming language. Although it is well suited for a wide variety of applications but that doesn’t leave web behind. It’s clean and elegant syntax plus the support of large library of standard and contributed modules makes it technically covering everything from parallel processing to simple tasks as read or write operation on a file. Also its object-oriented model makes it suitable for MVC style development.

If you’re like many people (yeah I’m in too) who first started with C and Java, the fact that python is easy to learn gets you to jump to the conclusion that python is not that necessary programming skill—I beg to differ—Python can actually push you to great heights whether it comes to landing a job or getting to taste the hottest trend in tech like Big Data, Machine learning etc.

The reason I’m falling in love with python is because it’s hard to mess up. The beauty of Python; besides its simplicity; is its readability, versatility, fast to write and there’re no ‘Black Holes’ in its design.

As far as the performance is concerned, Python runtime environment is one of its kinds. It is known to be fastest and stable besides having support for most of the famous web servers through modules. Python is also available for all major platforms: Windows, Mac, UNIX/Linux.

Why Django?

Probably as soon as MVC pattern developed it roots into web development, python provided quite a few choices for the web frames. Django is one of the available frameworks for python but the question is; which sets it apart from other frameworks and what makes it popular in python community?

If you’re a perfectionist but need to meet those deadlines (yeah I hate them too. Nobody likes the deadlines anyway. Right?) Django is the best option for you as everything falls in place and in no time. It was specifically made for people who want clear code and a good architecture for their applications. Below are few more reasons to consider Django.

Integration:

Django’s components were meant for integration, reusability and speed from the start. It started as an in-house framework for managing a series of news oriented websites but later its code was made public and Django team contributed its development using the Open Source model. So because of its roots, it provides tight integration between components.

ORM:

Django comes with Object-Relational Mapper (ORM) which is more like a connection between data model and database engine. So even if you’re no master at SQL only the basics would work perfectly fine with it. Also migrating data from one database engine to another is just a matter of changing a configuration file.

URL Design:

Django provides its user the convenience and flexibility allowing URL to be mapped using regular expressions. You can also define functions to handle each pattern. That means it works the both way; user as well as search engine friendly.

Administration interface:

One of the coolest things about Django is that it provides you a ‘built in’ administration interface. It’s just not only ready to use but also highly flexible and customizable.

 Some other cool features include security advice, internationalization or localization, huge community support and also extensive documentation which has your back in case you run into some mess. No doubt why those ‘High Load’ and popular projects like Pinterest and Instagram rely on python and Django in particular to provide users with stable, fast access.

  That’s it for the introduction part. Now let’s go ahead and see how to set the things up.

Setting up the environment

In order to get started with Django, you’ll need the following:

  • Python
  • Django
  • A database system

Just to be clear as being a windows user, I’ll only be covering installation on windows but installation is pretty similar for other platforms too like Linux.

Installing Python:

Django is written in python so very first step towards our development setup is the installation of python. Visit http://www.python.org/download/ and download the latest version of python according to your system. Next, execute the .exe file and follow the instructions. The graphical installer will guide you throughout. After the installation, just to check, open command prompt and enter the following command

$ python --version

If everything worked out perfectly, you should see the version of python you installed.

Getting Started with Django

Figure 1: Installing Python

Something about pip:

pip is like the package manager for Python. It will make installing and uninstalling Python packages (such as Django) very easy. To get pip on your machine just enter the following command at command prompt.

$ Python –m pip install –U pip

It will either let you know that pip is up to date or update it for you. For me, it is up to date so it shows something like this.

Getting Started with Django

Figure 2: Installing pip

Installing Django:

Now with everything set up, installing Django is super easy. Just enter the command

$ pip install Django

The above command will get the latest version of Django for you. Or if you want to install a specific version of Django, modify the command like this:

$ pip install Django==2.0.4

Easy right?

Time out Exception:

Watch out. If the above procedure doesn’t seem to work for you (as for me you see so many freaking red lines in response indicating time out exception). First thing; Don’t panic. It happens because there is too short default timeout set for pip by default. All we need is to change this default timeout and we’re good to go. Enter the following command:

$ pip --default-timeout=60 install django    # setting the default timeout to 60 (1 min)

or

$ export PIP_DEFAULT_TIMEOUT=60  $ pip install django

You can set this default timeout to whatever suits you.

If everything worked, go ahead, open the python shell and get the version of Django. It’s not mandatory but just for checking purposes.

Getting Started with Django

Figure 3: Installing Django

Installing Database system:

Django supports various database engines like MySQL, PostgreSQL, MS SQL Server, Oracle, and SQLite. But here’s another good feature about Django. If you are using the latest version of python, you won’t need to install any other database, since it comes with the SQLite database management system contained in a module named sqlite3. Using this module for deploying your site is not such a good idea but is great for learning and testing purposes. For the sake of simplicity, let’s just keep it this way.

Now you’re development setup is all done. Next step is of course creating your First Project.

Creating First Project

 Before actually creating our first project let me introduce you to the boss of Django “django-admin”. The reason I’m calling it a boss because this command-line utility is at the heart of Django’s project management facilities. You’ll need this utility to perform a bunch of administrative tasks including:

  • Creating a new project.
  • Starting the development web server.
  • Creating and managing the project’s database.
  • Validating the current project and testing for errors.

Now let’s get started.

Creating a new project:

To create your project, open command prompt and navigate to the location on your drive where you want to create the project. Now execute the following command.

$ django-admin startproject website       # website is the name of project. You can choose any name for your project.

What this command does is, it will make a folder name ‘website’ in the current directory. This folder also contains initial directory structure for our project inside it.

Getting Started with Django

Figure 4: Creating Project

Now that our project is created; before exploring the content of this folder; let’s take a moment and talk about the IDEs.

 Python is a simple language and a plain text editor such as Vim, Emacs, or Sublime Text works fine but they simply focus on the editing of a single file which is lean-and-mean but when it comes to develop complex application then it’s quite frightening for me to even think about text editors. (Ok I never ever used a text editor. Not a fan.). Whereas Integrated Development Environment (IDE) has a broad vision. They look at the whole project at once and unify all coding related activities. IDEs also have plus points like Auto-completion, quick syntax error fixes, code navigation and even smart assistance addressing the semantics of your code.

There are bunch of IDEs to choose from. Some of the most commonly used IDEs are

  • PyCharm by JetBrains
  • Visual Studio Code by Microsoft
  • PyDev for Eclipse

Personally I’ve been using PyCharm and I love it. It seems friendlier to me, easy to install and use. For the rest of the article, I’ll be working with PyCharm. Things are not so different for any IDE you choose so no worries pal.

Project Exploration:

Let’s continue where we left, open your newly created project. The first file you’ll come across is manage.py.

manage.py:

This file would be created automatically every time you create a project. It can be thought of performing the same thing as django-admin but just for this project. If you open this file with any text editor or IDE, the code just looks something like this.   

#!/usr/bin/env python  import os  import sys   if __name__ == "__main__":      os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")      try:          from django.core.management import execute_from_command_line      except ImportError as exc:          raise ImportError(              "Couldn't import Django. Are you sure it's installed and "              "available on your PYTHONPATH environment variable? Did you "              "forget to activate a virtual environment?"          ) from exc      execute_from_command_line(sys.argv)

It put your project’s package on sys.path and sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project’s settings.py file. It also checks for proper Django installation. If it fails to import the Django, it will raise an error asking if you’ve installed the Django and is available on your python environment.

Next, open the sub folder with the same name that of your project. Let’s go through each file one by one.

__init__.py

Assuming you have the basic knowledge of python, don’t merely think of this special __init__ method to be constructor for python.  If you open it you’ll see that It doesn’t contain any code but its presence tells python that this whole folder is to be treated as a package. Technically, Django projects are no more than python package.

setting.py

This is the main configuration file of your project; generally speaking; including all the settings needed for your project to run successfully. Let’s go through the sections of this file one by one.

"""  Django settings for website project.   Generated by 'django-admin startproject' using Django 2.0.4.   For more information on this file, see  https://docs.djangoproject.com/en/2.0/topics/settings/   For the full list of settings and their values, see  https://docs.djangoproject.com/en/2.0/ref/settings/  """   import os   # Build paths inside the project like this: os.path.join(BASE_DIR, ...)  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

In the above part of your settings.py, BASE_DIR is pointing to the absolute path of the parent directory. 

# Quick-start development settings - unsuitable for production  # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/   # SECURITY WARNING: keep the secret key used in production secret!  SECRET_KEY = //long string of some characters

The above part specifies the security key for your project. Django provides you a cryptographic signing API to any app for cryptographically-secure signatures on vales and this security-key is used to makes hashes. It is also used to manage user session, password reset requests, messages, CookieStorage or FallbackStorage. It is important to keep this key secrect or attackers could use it to generate their own signed values.

# SECURITY WARNING: don't run with debug turned on in production!  DEBUG = True

By default, Django leaves the DEBUG = True. If your app raises an exception when DEBUG is True, Django will display a detailed traceback, including a lot of metadata about your environment, such as all the currently defined Django settings (from settings.py). But here’s a catch. NEVER DEPLOY A SITE INTO PRODUCTION WITH DEBUG TURNED ON. It’s a gaping hole for security as well as will rapidly consume memory on a production server.

ALLOWED_HOSTS = []

When Debug = False, Django Doesn’t Work at All Unless You Populate Allowed_hosts With a Suitable Value. This Setting Is Required to Prevent an Attacker From Poisoning Caches and Password Reset Emails With Links to Malicious Hosts by Submitting Requests With a Fake Http Host Header. So Django Will Only Allow Access to the Hosts That Are Allowed in This Section. if You’re Working With Tutorials or Just Building With Debug=false, You Can Specify It to Local Host and Everything Will Work Fine.

ALLOWED_HOSTS = [‘localhost’, ‘127.0.0.1’]

# Application definition   INSTALLED_APPS = [      'django.contrib.admin',      'django.contrib.auth',      'django.contrib.contenttypes',      'django.contrib.sessions',      'django.contrib.messages',      'django.contrib.staticfiles',  ]

This section lists all the applications that are enabled in this Django installation. Next, whenever we’ll create an app in our project, we would have to add it in this list to let the Django know and allow our app to run.

MIDDLEWARE = [      'django.middleware.security.SecurityMiddleware',      'django.contrib.sessions.middleware.SessionMiddleware',      'django.middleware.common.CommonMiddleware',      'django.middleware.csrf.CsrfViewMiddleware',      'django.contrib.auth.middleware.AuthenticationMiddleware',      'django.contrib.messages.middleware.MessageMiddleware',      'django.middleware.clickjacking.XFrameOptionsMiddleware',  ]

It lists all the active middleware in your project. Middleware is a framework of hooks into Django’s request/response processing. Each middleware listed above is responsible for doing some specific task.

ROOT_URLCONF = 'website.urls'

The above setting imports path to your root URLconf of your project. It can be overridden on a per-request basis and more paths can be specified.

TEMPLATES = [      {          'BACKEND': 'django.template.backends.django.DjangoTemplates',          'DIRS': [],          'APP_DIRS': True,          'OPTIONS': {              'context_processors': [                  'django.template.context_processors.debug',                  'django.template.context_processors.request',                  'django.contrib.auth.context_processors.auth',                  'django.contrib.messages.context_processors.messages',              ],          },      },  ]

Being a web framework, Django needs a convenient way to generate HTML dynamically and most common approach for it is templates. The above settings list the configurations for each engine. BACKEND is the path to the template engine class implementing Django’s template backend API. DIRS defines the list of directories where engine should look for template source file. APP_DIRS tells engine whether it should look for templates inside application. OPTIONS contains backend-specific settings.

WSGI_APPLICATION = 'website.wsgi.application'

It points to the application callable in website/wsgi.py. We’ll talk about the wsgi.py later in the article.

# Database  # https://docs.djangoproject.com/en/2.0/ref/settings/#databases   DATABASES = {      'default': {          'ENGINE': 'django.db.backends.sqlite3',          'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),      }  }

By default, Django comes with built in database, sqlite. The section above contains the settings for databases. You can also add other database engines like Mysql, sql server etc. 

# Password validation  # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators   AUTH_PASSWORD_VALIDATORS = [      {          'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',      },      {          'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',      },      {          'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',      },      {          'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',      },  ]

These settings apply some password validations to check for the user entered password. These validations include if the two passwords match, minimum length, common password (By default, it compares to an included list of 1000 common passwords) and all numeric. The cool thing about Django is that has password, user attributes validators so you don’t need to worry about it. Besides this it also lets you write your own validators. Pretty Cool. 

# Internationalization  # https://docs.djangoproject.com/en/2.0/topics/i18n/  LANGUAGE_CODE = 'en-us'  TIME_ZONE = 'UTC'  USE_I18N = True  USE_L10N = True  USE_TZ = True

Another cool feature of Django is internationalization. This feature enables your project to be presented in different time zones and different geographical locations. The above part of the settings is merely doing that. You can specify any language or time zone.

# Static files (CSS, JavaScript, Images)  # https://docs.djangoproject.com/en/2.0/howto/static-files/   STATIC_URL = '/static/'

Templates enable you to embed HTML code in you app but what about the formatting? These settings allow you to include any CSS files, images or JS files in your app. STATIC_URL tells Django where to look for these static files in the directory.

For now you have the basic overview of the settings. Let’s move on and explore the urls.py.

urls.py

This file is actually the mapping python functions with their URLs. The code generated by python is given below.

"""website URL Configuration  The `urlpatterns` list routes URLs to views. For more information please see:      https://docs.djangoproject.com/en/2.0/topics/http/urls/  Examples:  Function views      1. Add an import:  from my_app import views      2. Add a URL to urlpatterns:  path('', views.home, name='home')  Class-based views      1. Add an import:  from other_app.views import Home      2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')  Including another URLconf      1. Import the include() function: from django.urls import include, path      2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))  """  from django.contrib import admin  from django.urls import path   urlpatterns = [      path('admin/', admin.site.urls),  ]

Django comes with built-in admin panel. The above urlpatterns is mapping that panel to the URL. Whenever you create another view or template or add some other functionality to your project, you need to specify its URL in the above file.

wsgi.py

This file acts as the entry point for WSGI-compatible web server to serve the project.

"""  WSGI config for website project.  It exposes the WSGI callable as a module-level variable named ``application``.  For more information on this file, see  https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/  """  import os  from django.core.wsgi import get_wsgi_application  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")  application = get_wsgi_application()

Django’s primary deployment platform is WSGI, the Python standard for web servers and applications, so it sets up a simple default WSGI configuration for you. This file contains the application callable that application server uses to communicate with your code. Django uses the DJANGO_SETTINGS_MODULE environment variable to locate the appropriate settings module. If this variable isn’t set then wsgi.py will set it to website.settings. That’s how server discovers the default settings file by default.

By far, we have a pretty good understanding of the project files that we created now let’s move on and start our development server.

Starting the development server:

            We need a webserver to run our project but no worries. One of the coolest things about Django is that it comes with a pre-configured, lightweight web server for developing and testing applications. Django also supports other famous web server but for the sake of simplicity we’ll be using the built-in server.

To start the server, enter the following command:

$ python manage.py runserver 

Remember! You should be in the current project directory. You should see the following screen afterwards.

Getting Started with Django

Figure 5: starting the server

Next open your web browser and navigate to http://127.0.0.1:8000/ as specified in the above screen.

Getting Started with Django

Figure 6: running server

Congratulations!! Everything worked out perfectly.

Changing Port:

            As you might have noticed 8000 at the end of the URL. This actually is the default port for our server. If you want to change this port, just pass it as the command line argument. Like this:

$ python manage.py runserver 8080  # where 8080 is the new port specified to run the server.

Treat yourself. You just created your first project in Django. Although this project is dummy for the moment but a good start indeed. We’ll be adding functionality to our project in the next article.