DEV Community

Cindy Achieng
Cindy Achieng

Posted on • Edited on

How to set up Django Environment in Linux for beginners

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

What you will learn
  • Create a virtualenv test
  • Create a sample project called HelloDjango
  • Create a demo Django app called accounts
  • Finally configure the settings.py

    Let’s dive right in

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
Django Introduction

According to djangoProject,Django is a python web framework for developers looking for a faster way to build web applications and with less code.Essentially, django is for perfectionists with deadlines

Why Consider Django?

Please refer to the django Documentation for more info.I will give a personal opinion why it is really cool.

  • Inbuilt Security features such as Cross site request forgery (CSRF) protection.
  • Great Documentation.
  • Faster because It has many inbuilt features such as Admin site, Authentication
Linux Installation

I recommend Ubuntu or Debian .For this specific tutorial, I had mint installed because its light and it’s just a personal preference.

Python Installation

Django is a python framework so first ensure you have python installed.The default installed in my Os 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
Enter fullscreen mode Exit fullscreen mode

The above outputs

 Python 2.7.12
Enter fullscreen mode Exit fullscreen mode

To check the version of Python3

   $ python3 -V
Enter fullscreen mode Exit fullscreen mode

The above outputs

 Python 3.5.2
Enter fullscreen mode Exit fullscreen mode

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

$ python3 --version
Enter fullscreen mode Exit fullscreen mode

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.
>>> 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

to install the latest version 3.6 check this tutorial

Setting up Virtual Environment

We could just create a Django application on our computer, but to control the packages unique for our 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.use the command:

$ sudo pip install virtualenv
Enter fullscreen mode Exit fullscreen mode

Pip is a useful python package tool that installs, updates, and remove Python packages/libraries used by Django and your other Python apps.Pip come installed with python 2.7+downloaded from python website.You just have to upgrade it using the command:
$ pip install -U pip

You should get something like this if virtualenvis 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
Enter fullscreen mode Exit fullscreen mode
Create and name virtualenv

Once you have successfully installed virtualenv,next we create the virtualenv test in 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
Enter fullscreen mode Exit fullscreen mode

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 mustactivate it. change directory to your virtual environment using:

$  cd test
Enter fullscreen mode Exit fullscreen mode

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

 $ source bin/activate
Enter fullscreen mode Exit fullscreen mode

By now you should see your virtualenv in brackets

(test)  
Enter fullscreen mode Exit fullscreen mode

Below is a sample from my console:

(test) cindy@cindy-Veriton-M290 ~/test $ 
Enter fullscreen mode Exit fullscreen mode
How to check packages installed in the virtualenv you just created

run:

 $  pip freeze
Enter fullscreen mode Exit fullscreen mode
Django Installation

our virtualenv is running,let's install django .The version of django at the time of writing this article is 2.0.2.

$ pip install django
Enter fullscreen mode Exit fullscreen mode

Run:

  $ pip freeze 
Enter fullscreen mode Exit fullscreen mode

your console should list the installed packages

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

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 lets create our project Structure! Type this in your console:

django-admin startproject HelloDjango
Enter fullscreen mode Exit fullscreen mode

This command creates a template for our project.

HelloDjango/
    manage.py
    HelloDjango/
        __init__.py
        settings.py
        urls.py
        wsgi.py
Enter fullscreen mode Exit fullscreen mode

The outer HelloDjango is the container holding our project.Its okay to change the name to something else say ‘src'.

The inner HelloDjango contains your site's configurations.I Highly recommend you leave it as it is, at least for now.

Change to project directory

   cd  HelloDjango
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Make Migrations

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   
Enter fullscreen mode Exit fullscreen mode
Test development server

To test if your project is working well,go to your project 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 'achieng_website.settings'
 Starting development server at http://127.0.0.1:8000/
 Quit the server with CONTROL-C.
Enter fullscreen mode Exit fullscreen mode

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

SucessPage

Configuring Settings.py

We will make some changes on our settings.py.This file help us manage our static files such as css,js, and images.First we going to change Templates DIR

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
               ...
            ],
        },
    },
]
Enter fullscreen mode Exit fullscreen mode

Add staticfiles_Dirs as well:

      STATICFILES_DIRS = (
         os.path.join(BASE_DIR, 'static'),
      )
Enter fullscreen mode Exit fullscreen mode
Change time zone

Finally,lets go back to our settings.py and 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'
Enter fullscreen mode Exit fullscreen mode
Creating an App
 python manage.py startapp accounts
Enter fullscreen mode Exit fullscreen mode

Your project structure should be like this:

 accounts/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
   views.py
Enter fullscreen mode Exit fullscreen mode

The app creates modules such as models.py,admin.py,views.py,apps.py. Django implements MVC Pattern

For the app you have just created to be used,add it to INSTALLED_APPS in the settings.py.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
)
Enter fullscreen mode Exit fullscreen mode

This Post was originally posted onachiengBlog

Top comments (10)

Collapse
 
benjiemadolin profile image
benjie

Hello. Anybody experienced or encountered the error below? I need help. Thanks a lot!

$ python manage.py startapp TestApp
File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

Collapse
 
partha2000 profile image
Partha Prateem Patra

Yes this error usually occurs if you haven't activated the virtual environment.

Collapse
 
cindyachieng profile image
Cindy Achieng

Hello Benjie,

It has been a while, did you get help?

Collapse
 
xowap profile image
Rémy 🤖

Why using Django? Because the ORM is awesome and migrations are fucking dope. At this stage that's what makes me addicted to Django (versus any other framework that handles everything else just as well).

Collapse
 
benbb96 profile image
BBB

I want to add the useful pip freeze > requirements.txt in order to keep the list of the package and then pip install -r requirements.txt in order to install them (on another environment for example)

Collapse
 
takaakifuruse profile image
TakaakiFuruse

I've used Pipenv also for doing django tutorials and love it. If you familiar with Ruby, It's like a bundle.
You can add, remove, libraries very easily.
docs.pipenv.org/

Collapse
 
hug0albert0 profile image
Hugo Alberto Rivera Diaz • Edited

If you get the next error message while trying to create the virtualenv in Ubuntu:

Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 24, in
import distutils.spawn
ModuleNotFoundError: No module named 'distutils.spawn'

Just run: sudo apt-get install python3-distutils

This happens because Ubuntu's built-in Python is broken.

Collapse
 
cindyachieng profile image
Cindy Achieng

I am glad you think so ☺.No,I haven't used pipenv yet,and I am definitely trying it out.

Collapse
 
hasanmehdirizvi profile image
hasanmehdirizvi

Hi Cindy,

what after adding app? I followed your article and my django admin page is up but i have don't know what to do after creating app. How to access it? it is still showing me admin page.

Collapse
 
cindyachieng profile image
Cindy Achieng

Hi Hasan,

This tutorial was simply to help with setting up the Django structure.The app is where you should perform the task you wanted to.For example as the name suggests accounts app would be handling registration,password resets etc.

I have a tutorial called laughing blog and it can give you better perspective achiengcindy.com/blog/2018/06/23/l...