How to set up Django Environment in Linux for beginners

published on: | by cindy In category: Django

When I started learning Django, finding a tutorial that had everything I needed was pretty hard. Hopefully, this tutorial will help you get started!

Django, commonly referred to as 'The web framework for perfectionists with deadlines', was released in 2015 as open source and has since attracted a large community around it over the years. According to DjangoProject, it is a python web framework for developers looking for a faster way to build web applications faster, with less code and not worry about security. Django adopts Model-Template-View (MTV) pattern.

Why Consider Django?

If you ask most programmers why they choose to code in a certain language and not the other, the reasons are varied. Every programming language has an advantage or two over the other. Some like python is easy to master than others or depending on what you intend to achieve. It's more practical to learn java or Kotlin for Android developers as python for data scientists.I will give my personal opinion on why I recommend Django for any beginner in web development.

Secure

Django has taken into account security measures and offer developers features to prevent common attacks such as:

  • Cross-Site Request Forgery (CSRF) protection. CSRF or Sea Surf is a malicious attack on unsuspecting website users to execute illegitimate action taking advantage of the users authenticated status without their knowledge. The attackers take advantage of web servers without enough information about the request hence lack the ability to distinguish between a legitimate request from a forged one. Django offers an additional field with tokens put by the server on all POST requests so that the server only execute request if the tokens match
  • Cross Site Scripting(XSS)
  • SQL injection
  • clickjacking, etc

Great Documentation

Django has Detailed Documentation.It has been around since 2015 when it was released as open source and has attracted a community of developers around it. When you get stuck, there is a good chance someone else was too, so finding a solution is as easy as searching on the web and forums such as StackOverflow.

Speed

Django comes handy whenever speed is a factor. With so many built-in functionalities that could take more time to develop.

  • Built-in Admin interface
  • Authentication System
  • Templates and layouts
  • Object-Relational mapper (ORM).This is a database abstract API that let you create, retrieve, update and delete objects easily. It is compatible with MySQL, SQLite, Oracle, PostgreSQL.django allows you to use multiple databases by simply defining the databases you want to use in the projects settings file.
  • internationalization
  • Forms

Prerequisites

Make sure you have the following installed on your computer to follow-through. + You got Linux Os installed (Ubuntu, Debian) + Python 3+ + Django 2.0 + Virtualenv + pip

Note

We will use pip and virtualenv in this article , If you want to use pipenv,please refer to Pipenv.

Linux Installation

I recommend Ubuntu or Mint if you are new to Linux. For this specific tutorial, I had mint installed because it's light and friendly for any beginner.

Python Installation

Django is a python framework so first ensure you have python installed. The default installed in my OS(at the time of writing this article) is 2.7. Check the version of python installed by typing the following command into your shell:

python --version
python -V // mind the capital
python2 -V

If you run either of the codes above, your output should look something like this outputs Python 2.7.12

To check for Python3

python3 -V
python3 --version

The above outputs

Python 3.5.2

In this tutorial, we are using python 3.5 and higher. Type the command below to check which version 3 is installed

python3 --version

You should see something close to this:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license"  for more information.

At this point, you can type CTRL+D to exit the interactive shell for now. Installing Python If you do not have python installed, use this command:

sudo apt-get install python3.5

installing Python 3.6

to install the latest version 3.6 check this tutorial

Let’s dive right in What you will learn

  • Create a virtual environment a name it test
  • Create a sample project called HelloDjango
  • Create a demo Django app called accounts
  • Finally, configure the settings.py

Setting up Virtual Environment

We could just create a Django application on our computer, but to control the packages unique for the application we will use Virtual Enviroment. Virtual Environment is useful when you want to create isolated environments, each running their own versions of packages. We can even create virtual environments with various python versions! sounds cool. For this tutorial, I am going to use virtualenv.

Virtualenv

We can install virtualenv using python’s package manager pip

sudo pip install virtualenv //installing virtualenv using pip

What is pip

Pip is a useful python package tool that installs, updates, and remove Python packages/libraries.Pip come installed with python 2.7+ downloaded from python website.

Alternatively, use apt

sudo apt get virtualenv

You should get something like this if virtualenv< >is already installed as in my case:

cindy@cindy-Veriton-M290 ~/Desktop $ pip install virtualenv
Requirement already satisfied: virtualenv in /home/cindy/.local/lib/python2.7/site-packages

Create and name virtualenv

Once you have successfully installed virtualenv, next we create the virtualenv test in the shell. I like creating my project in documents Folder. So right-click and choose open a terminal here option. Once you open the terminal, type:

virtualenv -p python3 test

test is just a name, you could give it any name. The -p points to the python version you want to use, in the above case python 3 Activate Virtualenv

Now that we have created our virtualenv test, we need to use it to install Django and other packages we will need. In order to use our virtualenv, we must activate it. change directory to your virtual environment using:

cd  test

Then once you are inside the virtualenv directory, activate it as shown below:

source bin/activate

By now you should see your virtualenv in brackets (test) Below is a sample from my console:

(test) cindy@cindy-Veriton-M290 ~/test $

To check packages installed in the virtualenv you just created run:

pip freeze

Django Installation

Our virtualenv is up and running, it is time to install Django. The version of Django at the time of writing this article is 2.0.2.Run:

pip install Django

To check for the packages installed run:

pip freeze

your console should list the installed packages

(test) cindy@cindy-Veriton-M290 ~/test $ pip freeze
Django==2.0.2
pytz==2018.3

How to specify Django Version

To specify django version,use: pip install django==. For example to install django 1.11:pip install django==1.11

Creating Django Project

Django is successfully installed so let's create our project Structure. Type this in your console:

django-admin startproject HelloDjango

The startproject command will create a structure similar to the one below:

HelloDjango/
manage.py
HelloDjango/
__init__.py
settings.py
urls.py
wsgi.py

The structure may seem confusing at a glance but I will try to explain everything.

  • The outer HelloDjango is the container holding our project. It's okay to change the name to something else. I like using src because it's more intuitive.
  • The innerHelloDjangocontains your site's configurations. I Highly recommend you leave it as it is, at least for now.
  • __init__.py is an empty file that identifies the directory as a python module
  • settings.py This is a configuration file for your site. It tells Django where to find static files, allows you to choose your language, add apps created in order to activate them, specify the database, etc.This is a good place to put system-wide configurations.
  • urls.py This file is responsible for mapping incoming request to their respective responses
  • manage.py This file enables you to run various commands to administer your site.

Change to the project directory.

HelloDjango

Note

The project directory is the outer HelloDjango containing manage.py file. If you changed its name to src, then change directory to src.

cd src

Make Migrations and Run Test Server

We need to create a database and Django comes with SQLite.You are free to use any other databases of your choice. But for this tutorial, we will use the SQLite. Change directory to the project root and make migrations by typing the command:

python manage.py makemigrations
python manage.py migrate

Test development server

To test if your project is working well, go to your project's root directory then type this :

python manage.py runserver

You should see something like this:

Performing system checks...
System check identified no issues (0 silenced).
February 28, 2018 - 18:58:33
Django version 2.0.2, using settings
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

When you go to http://127.0.0.1:8000/,If Django was successfully installed you should get a success message "congratulations"

SucessPage

Create a Superuser

To Interact with the admin site, we must create a SuperUser.A superuser has admin privileges

python manage.py createsuperuser

Then input the credentials. Below is a snippet

Username: laughing-blog
Email address: 'email Adress'
Password:
Password (again):

Run the server and navigate to http://127.0.0.1:8000/admin on the browser.Log in using superuser credentials you created above

python manage.py runserver

Configuring Settings.py

For the project to work properly, we need to make some changes in settings.py.

Templates

First, we going to change the Templates DIR to look like this

'DIRS': [os.path.join(BASE_DIR, 'templates')],

This simply tells Django to look for the templates folder in the project's root directory.

Staticfiles

Django allows us to have static files tied to a particular app and it is already defined in the setting.py as STATIC_URL = '/static/'. In addition, we want to tell Django where to look for static files that are not tied to any particular app by defining STATICFILES_DIRS.

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]

Change time zone

Finally,let's change our timezone.I come from Nairobi so my time zone is Africa/Nairobi.Check yours on: wikipedia

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Nairobi'

Creating an App

Apps are small components that are used to build projects. Usually, they perform a specific task and can be reused in various projects. Create an app that manages user accounts and names it accounts by running the following command.

python manage.py startapp accounts //this app is called accounts

The app creates sub-modules such as models.py contain classes mapped to database tables admin.py views.py Contain the logic of your application. A python function(s) that take a web request ad return response apps.py __init__.py An empty file that simply tells Django to treat the directory as a python module

accounts/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

To use the app you have just created, activate it by adding it to INSTALLED_APPS in settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]

Conclusion

This can be overwhelming and so did awesome to reach this far. Most of the naming used are simply conventional and not a requirement. The installation and configurations above are ideal for large projects In a very small project, for example, urls.py can be included in any importable python module or views do not have to live inside views.py