This is the first post in the Django tutorials series. Today we’ll be learning about the Django environment and will set up our first Django web application on a localhost. This Django tutorial is for beginners who don’t have any idea about Django framework. Let’s get set and GO!.
Table of Contents
Django is a high-level web framework that’s written in Python. It’s free and open sourced and is used to develop web applications easily.
Why is Django so popular?
Django takes care of the common stuff of web development so that you can concentrate on writing the stuff that’s unique to your application. The framework provides you with pre-defined modules and tools so that you don’t reinvent the wheel every time.
Few features that make Django stand high in the web application development:
- Authentication: The Django system handles both authentication and authorization.
- URL Routing: Django lets you design easy URL routing.
- Security: Django takes care of the security of your web application. It enables protection against many vulnerabilities such as SQL Injection, cross scripting by default.
- Database Integration: Django takes care of database integration for us. The major databases that are primarily used with Django are PostgreSQL, MySQL, SQLite, and Oracle. SQLite is the default database. Though other third-party databases work well too.
- Database Migration: Django uses ORM to map objects to databases. Hence database migration is easy.
Besides Django is well documented and has a large community support. So no doubt that Django is so popular to develop web applications quickly and easily.
In the following section, we’ll develop a web application that displays “Hello World”. We’ll deploy it on our localhost.
Django Hello World Project
Python, Virtualenv and Django are the three major things that need to be installed for setting up our web application.
Make sure you’ve installed Python3 on your system. You can check that by running the following command on your system.
If you don’t have Python installed you can download it from their website.
On Mac OSX you can install it quickly using Homebrew:
brew install python3
Since Mac OS already comes with python. Installing python would keep both the Python2 and Python3 versions.
Installing Virtual Environment
Virtual Environment is used to isolate our Python and Django project from the rest of the system. To install
virtualenv, we’ll use the pip tool that comes with Python.
Run the following command in your terminal.
sudo pip3 install virtualenv
The following is the screenshot from my terminal:
Since I’d already installed it before, it won’t do it again for me. Ignore the warning.
Now we need to create our Project. Run the following commands in the terminal to create a new folder for your Python Django Project.
mkdir JournalDevHelloDjango cd JournalDevHelloDjango
Now add the virtual environment in this project using the following command:
virtualenv -p /usr/local/bin/python3 env
-p tells the virtual environment the path of the python we wish to use. We’re using python3 in this tutorial.
env is the environment name we’ve set. You can set any name in it’s place.
The terminal displays the following:
Once it’s done, we’re ready to start our Virtual Environment:
For mac osx we run the following command:
The terminal shows the following:
Note: For mac osx terminal the activate virtual environment name would be displayed in each command from now.
To stop the virtual environment, we need to run
deactivate in the terminal.
Don’t do this for now since we need to create our first application quickly.
Let’s install Django next.
Just execute the following command in your terminal to install Django.
pip3 install django
Congratulations if you’ve come so far! You’re all set to create your first Django project.
Create New Django Project
To create a new project in the virtual environment execute the following command:
django-admin startproject HelloDjango
django-admin is a built-in command.
Our project structure looks like this right now:
It consists of an inner folder with the same name i.e.
HelloDjango in this case.
Some of the pre-defined python files that are created are:
__init__.py: This indicates that this directory should be considered as a Python package.
settings.py: This file contains all the project’s configuration.
urls.py: This file is used for URL routing. It’s here where you’ll define the URL paths to different directories of your application.
wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. It’s just a gateway. We’ll look into this in a later tutorial.
manage.py: This is used to manage our Django project. Over this file, we’ll run commands to deploy, test our application as well as do database migrations if needed. It’s a command line utility. This file is present in the outer HelloDjango folder.
Run the following command to deploy the project onto the server.
python3 manage.py runserver
Ignore the migration errors.
By default, the server has started on port 8000.
Open the URL:
https://127.0.0.1:8000/ in your browser and you should see this:
python3 manage.py runserver 8080.
To run the server on all IPs present in the network do:
python3 manage.py runserver 0:8000
To stop the server do a
Ctrl + C.
Now let’s create a Hello World Django Web Application.
Creating a Django Web Application
A single Django project can contain one or more Django Apps.
settings.py file already consists of a few pre-defined installed Django Apps:
To create your own Django App goto the outer HelloDjango folder and run the following command in the terminal.
django-admin startapp helloworld
This creates a
helloworld app in our Django project.
Following is the structure of our project now:
Let’s look at the files in the Django App:
models.py: Entities of the Django App are defined here. These are translated into the database table.
migrations/: This folder stores file to keep track of database migration.
admin.py: This is the config file for the Django Admin App that’s auto-generated.
apps.py: This is a config file of the current application.
tests.py: Unit Tests of the Django App are written here.
views.py: This is used to display the view in our web app. It consists of a function that does a network request and gets back the response.
urls.py: This does the URL routing in the current app only. It’s different from the
urls.pyfile present in the project which can do URL dispatches at the project level. That means it can contain URL routing list of different apps.
__pycache__gets generated when the project is deployed on the server.
Now add the
helloworld app in the
settings.py file of our HelloDjango Project.
Let’s do something in our
views.py file now:
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def hello(request): return HttpResponse('Hello, World!, Django')
from django.shortcutsimport render is used to load the Django view template.
hellofunction returns a response that prints the string onto the screen.
URL Mapping refers to mapping URLs to Django Views. We use regular expressions and tuples for URL Mapping.
URL Mapping is done in the url.py Python file.
An example url.py file is given below:
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/', 'myapp.views.hello', name = 'hello'), url(r'^', include('example.urls')) # tell django to read urls.py in example app ]
- First Param: Regular Expression − The first parameter passed is typically a regular expression. r’ is followed by a ^. A ^$ refers to an empty path. That means root path.
Second Param: View Path − Here you pass the path to the View that’s triggered from that regular expression url. You can also include a new url router here which refers to a different Django app/module. For this
- Third param: url name − In order to do a reverse lookup, the name of the url path is passed.
path are the new keywords introduced since Django 2.0.
from django.urls import include, path, re_path
re_path() is similar to url()
path() is devoid of regular expressions.
url() would be deprecated in future.
Let’s do the URL routing so that this view is loaded instead of the previous Django documentation view.
urls.py in the inner HelloDjango project folder with the following code:
from django.contrib import admin from django.urls import urls from helloworld import views urlpatterns = [ url(r'^$', views.hello, name='hello'), url(r'^admin/', admin.site.urls), ]
^$ matches with an empty path. So the views.py would open on the homepage itself.
Woah! Finally we’ve created our first Django Project and a Hello World Web App.
Now you can kill the server using
Ctrl + C command. Then run
deactivate command to shutdown the virtual environment.
That’s all for Python Django tutorial for beginners.