How To Install the Django Web Framework 2 on Ubuntu 16.04

Posted on in Categories , , , last updated December 3, 2017

Django 2.0 released. How do I install it on the Ubuntu Linux 16.04 LTS server? How do I create a sample “Hello world” view and /admin/ section for Django 2.x?

Django is a free and open source Python web framework for creating web apps. In this tutorial, you will learn how install Django 2 on an Ubuntu Linux 16.04 LTS server including a quick starter for your site.

Install the latest version of Django 2.x

First you need to install pip for Python 3.x. Type the following apt command/apt-get command
$ sudo apt-get install python3-pip
Sample outputs:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  binutils build-essential ca-certificates cpp cpp-5 dpkg-dev fakeroot g++ g++-5 gcc gcc-5 libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan2 libatomic1 libc-dev-bin libc6-dev
  libcc1-0 libcilkrts5 libdpkg-perl libexpat1-dev libfakeroot libfile-fcntllock-perl libgcc-5-dev libgdbm3 libgomp1 libisl15 libitm1 liblsan0 libmpc3 libmpfr4 libmpx0 libperl5.22 libpython3-dev
  libpython3.5-dev libquadmath0 libstdc++-5-dev libtsan0 libubsan0 linux-libc-dev make manpages manpages-dev openssl patch perl perl-modules-5.22 python-pip-whl python3-dev python3-pkg-resources
  python3-setuptools python3-wheel python3.5-dev rename xz-utils
Suggested packages:
  binutils-doc cpp-doc gcc-5-locales debian-keyring g++-multilib g++-5-multilib gcc-5-doc libstdc++6-5-dbg gcc-multilib autoconf automake libtool flex bison gdb gcc-doc gcc-5-multilib libgcc1-dbg libgomp1-dbg
  libitm1-dbg libatomic1-dbg libasan2-dbg liblsan0-dbg libtsan0-dbg libubsan0-dbg libcilkrts5-dbg libmpx0-dbg libquadmath0-dbg glibc-doc libstdc++-5-doc make-doc man-browser ed diffutils-doc perl-doc
  libterm-readline-gnu-perl | libterm-readline-perl-perl python-setuptools-doc
The following NEW packages will be installed:
  binutils build-essential ca-certificates cpp cpp-5 dpkg-dev fakeroot g++ g++-5 gcc gcc-5 libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan2 libatomic1 libc-dev-bin libc6-dev
  libcc1-0 libcilkrts5 libdpkg-perl libexpat1-dev libfakeroot libfile-fcntllock-perl libgcc-5-dev libgdbm3 libgomp1 libisl15 libitm1 liblsan0 libmpc3 libmpfr4 libmpx0 libperl5.22 libpython3-dev
  libpython3.5-dev libquadmath0 libstdc++-5-dev libtsan0 libubsan0 linux-libc-dev make manpages manpages-dev openssl patch perl perl-modules-5.22 python-pip-whl python3-dev python3-pip python3-pkg-resources
  python3-setuptools python3-wheel python3.5-dev rename xz-utils
0 upgraded, 57 newly installed, 0 to remove and 0 not upgraded.
Need to get 86.3 MB of archives.
After this operation, 245 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.ubuntu.com/ubuntu xenial/main amd64 libgdbm3 amd64 1.8.3-13.1 [16.9 kB]
Get:2 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 perl-modules-5.22 all 5.22.1-9ubuntu0.2 [2661 kB]
...
....
..

Use the pip3 command as follows to install django
$ sudo pip3 install Django
OR
$ sudo pip3 install Django==2.0
Sample outputs:

Fig.01: Install Django 2.x using pip/pip3 command
Fig.01: Install Django 2.x using pip/pip3 command

Verify your installation by typing the following simple command:
$ django-admin --version
OR
$ python3 -m django --version
Sample outputs:

2.0

Creating user accounts for new project

Use the useradd command to create a new user named cbzdjango for my project:
$ sudo useradd -c 'Cyberciti.biz app root' -d /home/httpd/ -m -s /bin/bash cbzdjango
$ sudo passwd cbzdjango

Where,

  1. -c 'description' : Set GECOS for the new account
  2. -d /home/httpd/ : Set home directory for the new account
  3. -m : Create home dir for the new account
  4. -s /bin/bash : Set bash shell for the new account

Put your django 2.x code in some directory outside of the document root, such as /home/httpd instead of default /var/www/html. This is a security feature. Now you can login using ssh command or su command
$ ssh [email protected]
OR
$ su – cbzdjango

Writing your first Django 2.x app

First you need to auto-generate some code that establishes a Django 2.x project using the django-admin command. The syntax is:
$ django-admin startproject Your-Project-Name-Here
$ cd Your-Project-Name-Here

For example, I am going to create a project named helloworld

$ django-admin startproject helloworld
$ ls -l
total 4
drwxrwxr-x 3 cbzdjango cbzdjango 4096 Dec  3 17:04 helloworld
$ cd helloworld
$ ls -l
total 8
drwxrwxr-x 2 cbzdjango cbzdjango 4096 Dec  3 17:04 helloworld
-rwxr-xr-x 1 cbzdjango cbzdjango  542 Dec  3 17:04 manage.py

Next you start the development server by typing the following command in the helloworld directory:
$ python3 manage.py runserver
Sample outputs:

Performing system checks...
 
System check identified no issues (0 silenced).
 
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.
 
December 03, 2017 - 17:13:44
Django version 2.0, using settings 'helloworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

To change the server ip and port, run:
$ python3 manage.py runserver 8443
$ python3 manage.py runserver 0.0.0.0:8443
$ python3 manage.py runserver 10.98.222.14:8443

If you change the port and IP, make sure you update settings.py as follows to avoid the following error:

DisallowedHost at /
Invalid HTTP_HOST header: '10.98.222.14:8443'. You may need to add '10.98.222.14' to ALLOWED_HOSTS.
http://10.98.222.14:8443

Edit helloworld/settings.py
$ vi helloworld/settings.py
Set/update/edit ALLOWED_HOSTS as follows:

ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '192.168.2.115', '10.98.222.14' ]

Save and close the file. Start the server again:
$ python3 manage.py runserver 10.98.222.14:8443
Fire a web browser and type the following url:
http://10.98.222.14:8443
Sample outputs:

Fig.01: Yay! The install worked successfully on my server.
Fig.01: Yay! The install worked successfully on my server.

Writing your first view

First, make sure you’re in the same directory as manage.py and type the following command:
$ python3 manage.py startapp demo
$ ls -l

Sample outputs:

Fig.03: Creating the demo app
Fig.03: Creating the demo app

Above will create a directory demo, which is laid out like this:

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

This directory structure will hold the demo application. Next edit file as follows:
$ vi demo/views.py
Edit/append as follows:

from django.shortcuts import render
 
# Create your views here.
from django.http import HttpResponse
 
 
def index(request):
    return HttpResponse("Hello, world. Yay! My first app is online.")

Save and close the file. This is the simplest view possible in Django and simple display “Hello, world. Yay! My first app is online.”. To call the view, you need to map it to a URL
$ vi demo/urls.py
Append the following code:

from django.urls import path
 
from . import views
 
urlpatterns = [
    path('', views.index, name='index'),
]

Save and close the file. Finally update urls.py in your project directory:
$ vi helloworld/urls.py
Edit/append as follows:

"""helloworld 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
from django.conf.urls import include
 
urlpatterns = [
    path('demo/', include('demo.urls')),
    path('admin/', admin.site.urls),
]

Save and close the file. Start the server again:
$ python3 manage.py runserver 10.98.222.14:8443
Fire a browser and type the following command url:
http://10.98.222.14:8443/demo/
Sample outputs:

Fig.04: Your first "Hello World" app in Django 2.x in action
Fig.04: Your first “Hello World” app in Django 2.x in action

How to bootstrap the database and create /admin/ part for app

Type the following command to use the default sqlite3 db engine:
$ python3 manage.py migrate
Sample outputs:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

Creating an admin user

Type the following command:
$ python3 manage.py createsuperuser
Sample outputs:

Username (leave blank to use 'cbzdjango'): admin
Email address: [email protected]
Password: 
Password (again): 
Superuser created successfully.

Start the development server, run:
$ python3 manage.py runserver 10.98.222.14:8443
Fire a Web browser and go to “/admin/” url on your local ip/domain:
http://10.98.222.14:8443/admin/
You should see the admin’s login screen:

Fig.05: /admin/ url in action
Fig.05: /admin/ url in action

Type the admin username and password that you created earlier. You should see the admin section of the site as follows:
Fig.06: The admin site in action
Fig.06: The admin site in action

Conclusion

And there you have it, Django 2.x installed on your Ubuntu Linux 16.04 server, working with a sample demo application. I suggest that you take a look at the following resources if you want to learn or master Django:

  1. Django project home page
  2. Django books for learning and mastering Django
  3. Python 3 books for learning and mastering Python 3.x

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 6 comments/add one below):

6 comment

  1. sudo useradd -c ‘Cyberciti.biz app root’ -d /home/httpd/ -m -s /bin/bash

    did not work for me on my server do I need to own the domain or buy a domain and substitute it because for now I am just using a virtual server with an IP address that I can just get a domain for.

    best,

  2. I love the tutorial but I want to make it where have the server up and running. This tut teaches you how to make the install and setup but not the last part where the server is completely up and running. That would truly make this tutorial complete.

Leave a Comment