Your first Django Application

                 

Do you want to learn Django? OK! This is the right place for you!
In this article I will introduce you the most famous Phyton Web Framework with a learning-by-doing approach.
We will see a brief introduction about what Django is, we will see installation steps and we will create a simple application implementing some basics skills.

What is Django?

Django is an open-source Phyton Web Framework for creating secure and maintainable websites.
Django has been around since the 2005 and from there, it’s community has incrased as much as its popularity in the web development world.

It’s a common knowledge among the backend developers community and it’s still used in large scale.

These are some benefits you get using Django from the MDN web docs:

Complete
Django follows the “Batteries included” philosophy and provides almost everything developers might want to do “out of the box”. Because everything you need is part of the one “product”, it all works seamlessly together, follows consistent design principles, and has extensive and up-to-date documentation.
Versatile
Django can be (and has been) used to build almost any type of website — from content management systems and wikis, through to social networks and news sites. It can work with any client-side framework, and can deliver content in almost any format (including HTML, RSS feeds, JSON, XML, etc). The site you are currently reading is based on Django!
Internally, while it provides choices for almost any functionality you might want (e.g. several popular databases, templating engines, etc.), it can also be extended to use other components if needed.
Secure
Django helps developers avoid many common security mistakes by providing a framework that has been engineered to “do the right things” to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash.
A password hash is a fixed-length value created by sending the password through a cryptographic hash function. Django can check if an entered password is correct by running it through the hash function and comparing the output to the stored hash value. However due to the “one-way” nature of the function, even if a stored hash value is compromised it is hard for an attacker to work out the original password.
Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and clickjacking (see Website security for more details of such attacks).ScalableDjango uses a component-based “shared-nothing” architecture (each part of the architecture is independent of the others, and can hence be replaced or changed if needed). Having a clear separation between the different parts means that it can scale for increased traffic by adding hardware at any level: caching servers, database servers, or application servers. Some of the busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and Disqus, to name just two).
Maintainable
Django code is written using design principles and patterns that encourage the creation of maintainable and reusable code. In particular, it makes use of the Don’t Repeat Yourself (DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django also promotes the grouping of related functionality into reusable “applications” and, at a lower level, groups related code into modules (along the lines of the Model View Controller (MVC) pattern).
Portable
Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavours of Linux, Windows, and Mac OS X. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites.
source: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction

Phyton

Like every frameworks, Django has its own core language, Python.

Python is a high level, general purpose programming language used to create a huge number of applications, from games to websites.

If you have some Python skills, cool, they will be helpfull to understand better Django codes and if you don’t have any skills, don’t worry, you will learn the essential needs for running a Django application but I recommend you to start learning python by yourself.

Let’s see which beautiful features you get when using Python:

  1. Easily readable syntax.
  2. Awesome community around the language.
  3. Easy to learn.
  4. Python is useful for a myriad of tasks from basic shell sripting to advanced web development.

Some code examples:

This line of code will print “Hello, World!” in your terminal

# 
print("Hello, World!")

Simple conditional logic

# read in age
age = int(input("What's your age?"))

if age >= 18:
print("Access allowed")
elif age < 18 and age > 0:
print("Access not allowed")
else:
print("Invalid age")

Easy abstract data type

# create a list called my_list
my_list = [1, 2, 3, "python", 67, [4, 5]]

# go through my_list and print every item
for item in my_list:
print item
#a second way
print(my_list[3])

Installation

Here are our steps for setting up Django.
In this project I’m working with a Windows environment.

1 Download and Installing Python
2 Setting up the virtual environment
3 Installing Django

Download and Installing Python

First of all we need Python installed on our pcs.
For this project I’m using the currently latest version 3.6.4,
you can download here.
Inside the page there are the instructions for each operation system, so choose your OS and install Python.
Now, for checking if it’s setup correctly, open your command prompt and type

python

or

py

You should see something like this

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.

Then we need the Python Package Index tool, pip, but starting from Python 2.7.9, the command pip is included by default.

Setting up the virtual environment

Setting up a virtual environment helps you manage Python and Django packages indipendently.

It depends on which type of projects you will develop, but the best way is to manage all of your projects setting up their own environments each time.
You can manage Django and third-party packages and dependencies also globally but if you want to create projects with different versions of them you can’t, unless you unistall your current version and install the one you desire.

First, let’s get virtualenvwrapper installed with pip

pip install virtualenvwrapper-win

So create a wrapper folder which will contain the virtual environment and our application

mkdir helloWorld

Then create the virutal environment

mkvirtualenv helloWorldenv

Now you should see the environment prefix in your cmd

(helloWorldenv)

There are some usefull commands you can use :

  • deactivate — Exit out of the current Python virtual environment
  • workon — List available virtual environments
  • workon name_of_environment — Activate the specified Python virtual environment
  • rmvirtualenv name_of_environment — Remove the specified environment.

Type workon in your command prompt and now you should see all of the environments set, in our case only one, helloWorldenv

Pass a name to activate one of the following virtualenvs:
========================================
helloWorldenv

Type workon helloWorldenv if you not see the prefix.

Installing Django

Now you are inside the virtual environment and we can finally install Django

pip install django

Check the correct installation and the version

py -3 -m django --version

If you have not had any errors during the installation process, we are ready to create your first Django application.

Creating the Hello World application

Now that all the thing are setup, we are inside the environment folder and we can lunch our first Django command to initialize the application

django-admin startproject helloWorld

Now you should have this project folder

helloWorld //virtual environment folder
helloWorld
├─helloWorld
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py

This is your main project folder and contains the project’s settings in a file called settings.py and the routes in your project in the file called urls.py.

Now let’s run our server and see what will be the output

python manage.py runserver

You should see this

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate’ to apply them.
February 06, 2018–15:20:30
Django version 2.0.2, using settings ‘helloWorld.settings’
Starting development server at
http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

in your command prompt and in your browser, at http://127.0.0.1:8000/ address, you should see the Django welcome page

Creating the Hello application

Next, run the following command to create the hello application that will live inside our helloWorld project application.

We need to lunch the next command inside the django application folder, so verify if you are in the correct place. Without counting the wrapper folder, you need to be in the project higher folder (the one which has the manage.py file).

Now lunch this command to create your own app inside the project

python manage.py startapp hello

After you should have a structure like this

helloWorld
├── helloWorld
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── hello
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── manage.py

Django apps follow the Model, View, Template paradigm which is practically like MVC but they change Views with Templates and called it MTC.

To get Django to recognize our new app, we need to modify and add the app name in the list of installed app inside the settings.py file

https://medium.com/media/7206beb266837ff51d8f585f4affb163/href

Urls

Now we want our hello app displayed at the homepage of our application.
For that, we need to define a URL which will tell Django where to look for the homepage template.

Open the hello\urls.py file inside the helloWord folder

https://medium.com/media/9888ce0c22c34c359d25ff7e8c0bfee9/href

As you can see, there is an existing URL pattern for the Django admin site which comes by default with Django. Let’s add our own url to point to our hello app. Edit the file to look like this

https://medium.com/media/867555be80596f2c087e51550f97064f/href

If in your cmd is still running the Django development server, you will see this error

ImportError: No module named 'hello.urls'

It’s because we need to create the urls.py file inside the hello folder and while we’re here, let’s also create the templates folder which we will use after.
This should be your hello app folder

├── hello
│├── __init__.py
│├── admin.py
│├── apps.py
│├── migrations
│├── models.py
│├── tests.py
│├── views.py
│├── urls.py
│├── templates

Open hello\urls.py and write this

https://medium.com/media/6d8c9d8bcef9de88b8fbd2381adda080/href

This code imports the views from our hello app and expects a view called HomePageView to be defined. Since we don't have one, open the views.py file in the hello app and write this code

https://medium.com/media/bad2fdbcd8390eab397bd6ea94d7b6a5/href

This file defines a view called HomePageView. Django views take in a request and return a response. In our case, the method get expects a HTTP GET request to the url defined in our urls.py file. On a side note, we could rename our method to postto handle HTTP POST requests.

Once a HTTP GET request has been received, the method renders a template called index.html which is just a normal HTML file which could have special Django template tags written alongside normal HTML tags.

Now if you don’t want this error

templates\index.html file doesn’t exist

you need to create an index.html inside the /templates folder we created before, and insert this simple Html snippet.

https://medium.com/media/11c50431d773e5681d519b312de8f310/href

Now run your server.

python manage.py runserver

You should see your template rendered.

You created your first Django application! It’s pretty simple but with that, you learned some good stuffs about Django, from its installation to showing something custom on the screen.

If you enjoyed the article or if you think it was helpfull for you, please leave a “clap” and subscribe to my profile and also in the Devuality pubblication, we’ll post awesome backend and frontend resources for newbies and heroes developers.