By Jeremy Morris and Lisa Tagliaferri
Django is a free and open-source web framework written in Python that adheres to the model template view (MTV) software architectural pattern. The MTV pattern is Django’s take on the model–view–controller (MVC) pattern. According to the Django Software Foundation, the model is the single definitive source of your data, the view describes the data that gets represented to the user via a Python callback function to a specific URL, and the template is how Django generates HTML dynamically.
Django’s core principles are scalability, re-usability and rapid development. It is also known for its framework-level consistency and loose coupling, allowing for individual components to be independent of one another. Don’t repeat yourself (DRY programming) is an integral part of Django principles.
In this tutorial, we will set up a Django development environment. We’ll install Python 3, pip 3, Django and virtualenv
in order to provide you with the tools necessary for developing web applications with Django.
A non-root user account with sudo
privileges set up on a Debian or Ubuntu Linux server. You can achieve these prerequisites by following and completing the initial server setup for Debian 8, or steps 1-4 in the initial server setup for Ubuntu 16.04 tutorial.
To install Python we must first update the local APT repository. In your terminal window, we’ll input the command that follows. Note that the -y
flag answers “yes” to prompts during the upgrade process. Remove the flag if you’d like the upgrade to stop for each prompt.
When prompted to configure grub-pc
, you can press ENTER
to accept the default, or configure as desired.
It is recommended by the Django Software Foundation to use Python 3, so once everything is updated, we can install Python 3 by using the following command:
To verify the successful installation of Python 3, run a version check with the python3 command:
The resulting output will look similar to this:
Outputpython 3.5.2
Now that we have Python 3 installed, we will also need pip in order to install packages from PyPi, Python’s package repository.
To verify that pip was successfully installed, run the following command:
You should see output similar to this:
Outputpip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)
Now that we have pip installed, we have the ability to quickly install other necessary packages for a Python environment.
virtualenv is a virtual environment where you can install software and Python packages in a contained development space, which isolates the installed software and packages from the rest of your machine’s global environment. This convenient isolation prevents conflicting packages or software from interacting with each other.
To install virtualenv, we will use the pip3 command, as shown below:
Once it is installed, run a version check to verify that the installation has completed successfully:
We should see the following output, or something similar:
Outputvirtualenv 20.0.20 from /home/sammy/.local/lib/python3.5/site-packages/virtualenv/__init__.py
You have successfully installed virtualenv.
At this point, we can isolate our Django web application and its associated software dependencies from other Python packages or projects on our system.
There are three ways to install Django. We will be using the pip method of installation for this tutorial, but let’s address all of the available options for your reference.
Option 1: Install Django within a virtualenv
.
This is ideal for when you need your version of Django to be isolated from the global environment of your server.
Option 2: Install Django from Source. If you want the latest software or want something newer than what your Ubuntu APT repository offers, you can install directly from source. Note that opting for this installation method requires constant attention and maintenance if you want your version of the software to be up to date.
Option 3: Install Django Globally with pip. The option we are going with is pip 3 as we will be installing Django globally.
We’ll be installing Django using pip within a virtual environment. For further guidance and information on the setup and utilization of programming environments, check out this tutorial on setting up a virtual environment.
While in the server’s home directory, we have to create the directory that will contain our Django application. Run the following command to create a directory called django-apps
, or another name of your choice. Then navigate to the directory.
While inside the django-apps
directory, create your virtual environment. Let’s call it env
.
Now, activate the virtual environment with the following command:
You’ll know it’s activated once the prefix is changed to (env)
, which will look similar to the following depending on what directory you are in:
Within the environment, install the Django package using pip. Installing Django allows us to create and run Django applications. To learn more about Django, read our tutorial series on Django Development.
Once installed, verify your Django installation by running a version check:
This, or something similar, will be the resulting output:
Output2.2.12
With Django installed on your server, we can move on to creating a test project to make sure everything is working correctly.
To test the Django installation, we will be creating a skeleton web application.
First, if applicable, we’ll need to open the port we’ll be using in our server’s firewall. If you are using UFW (as detailed in the initial server setup guide), you can open the port with the following command:
If you’re using DigitalOcean Firewalls, you can select HTTP
from the inbound rules. You can read more about DigitalOcean Firewalls and creating rules for them by reading the inbound rules section of the introductory tutorial.
We now can generate an application using django-admin
, a command line utility for administration tasks in Python. Then we can use the startproject
command to create the project directory structure for our test website.
While in the django-apps
directory, run the following command:
Note: Running the django-admin startproject <projectname>
command will name both project directory and project package the <projectname>
and create the project in the directory in which the command was run. If the optional <destination>
parameter is provided, Django will use the provided destination directory as the project directory, and create manage.py
and the project package within it.
Now we can look to see what project files were just created. Navigate to the testsite
directory then list the contents of that directory to see what files were created:
Outputmanage.py testsite
You will notice output that shows this directory contains a file named manage.py
and a folder named testsite
. The manage.py
file is similar to django-admin
and puts the project’s package on sys.path
. This also sets the DJANGO_SETTINGS_MODULE
environment variable to point to your project’s settings.py
file.
You can view the manage.py
script in your terminal by running the less
command like so:
When you’re finished reading the script, press q
, to quit viewing the file.
Now navigate to the testsite
directory to view the other files that were created:
Then run the following command to list the contents of the directory:
You will see four files:
Output__init__.py settings.py urls.py wsgi.py
Let’s go over what each of these files are:
__init__.py
acts as the entry point for your Python project.settings.py
describes the configuration of your Django installation and lets Django know which settings are available.urls.py
contains a urlpatterns
list, that routes and maps URLs to their views
.wsgi.py
contains the configuration for the Web Server Gateway Interface. The Web Server Gateway Interface (WSGI) is the Python platform standard for the deployment of web servers and applications.Note: Although a default file was generated, you still have the ability to tweak the wsgi.py
at any time to fit your deployment needs.
Now we can start the server and view the website on a designated host and port by running the runserver
command.
We’ll need to add your server ip address to the list of ALLOWED_HOSTS
in the settings.py
file located in ~/test_django_app/testsite/testsite/
.
As stated in the Django docs, the ALLOWED_HOSTS
variable contains “a list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations.”
You can use your favorite text editor to add your ip address. For example, if you’re using nano
, just simply run the following command:
Once you run the command, you’ll want to navigate to the Allowed Hosts Section of the document and add your server’s IP address inside the square brackets within single or double quotes.
You can save the change and exit nano by holding down the CTRL
+ x
keys and then pressing the y
key.
With this completed, be sure to navigate back to the directory where manage.py
is located:
Now, run the following command replacing the your-server-ip text with the IP of your server:
Finally, you can navigate to the below link to see what your skeleton website looks like, again replacing the highlighted text with your server’s actual IP:
http://your-server-ip:8000/
Once the page loads, you’ll receive a webpage that is similar to the following:
This confirms that Django was properly installed and our test project is working correctly.
When you are done with testing your app, you can press CTRL
+ C
to stop the runserver
command. This will return you to the your programming environment.
When you are ready to leave your Python environment, you can run the deactivate
command:
Deactivating your programming environment will put you back to the terminal command prompt.
In this tutorial you have successfully upgraded to the latest version of Python 3 available to you via the Ubuntu APT repository. You’ve also installed pip 3, virtualenv
, and django
.
You now have the tools needed to get started building Django web applications.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Please add a section showing us the use of something like screen to keep the server running even when we close PUTTY or the terminal.
Hey @subhadeep , sorry for the late response. I did some quick research, and found another DO thread where a solution was provided to a similar problem. There’s also a tutorial on how to use screen here on DO. I hope this helps!
thank you for this. great help .
No problem, I’m glad it helped you!
i m unable to runserver in terminal. it shows a bunch of result and then syntax error.
Thank you for the feedback. What is the exact result and error you received?
File “/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py”, line 50, in include urlconf_module = import_module(urlconf_module) File “/usr/lib/python2.7/importlib/init.py”, line 37, in import_module import(name) File “/home/dania/Trial/polls/urls.py”, line 1, in <module> from django.conf.urls import patterns,url ImportError: cannot import name patterns
like these list of errors i received…
Same error. please help
first, you need to migrate databases. Just run “python3 manage.py migrate” After that, you can run “python3 manage.py runserver”
Thank you very much, Jeremy, Lisa… nice work!
Thank you for the feedback. I’m glad this tutorial was of help to you!
how to get to production follow by this set up ?
yes! redis and rabbitmq production setup stuff should be great too :)
Question : Isn’t the One-Click apps (Django 1.8.7 on 16.04) suppose to install Django For you ?
Yes. But this tutorial is for people working on a vanilla Ubuntu server and are interested in doing the Django setup themselves. If you’re interested in one-click deployments with pre-configured development environments for a Django app, I’d recommend this tutorial on how to use DigitalOcean’s one-click Django install.
Thank you for the quick reply. I used the One-Click Application. typed Python3
Np! And it should be
import django
For those who are following this tutorial, you might encounter an error on Step 2. Basically the error occurs when you tried to use the command “pip3 install”.
You simply need to run the following to fix this error:
Long answer can be found here: https://stackoverflow.com/questions/36394101/pip-install-locale-error-unsupported-locale-setting
@jeremylevanmorris : Please update this tutorial for the new users not to get stuck on Step 2.
Hey @lauretagabriel , thank you for your feedback. I am not able to replicate your issue. I am using the Ubuntu 16.04 DigitalOcean droplet. As long as you follow the prerequisites, step 1 and step 2 exactly in this tutorial, there will be no problems running
pip3 install virtualenv
.For example, here are my locale settings before and after installing
virtualenv
withpip3
.I appreciate the feedback!
if you run into problems
This won’t work if you’re using a cloud hosted server. Hence the
your-server-ip:8000
. If you’re running the Django app locally, the server IP may be localhost(loopback address, used to establish an IP connection to the same machine), 127.0.0.1(localhost a.k.a the loopback address) or 0.0.0.0(listens for all IPv4 addresses on the local machine). But if you’re using a cloud hosted server, the server IP value is the IP address of your server.I appreciate your feedback @GobBluth. If you have anymore issues let me know. Thank you!
Nicely explained for beginners. Thanks for sharing.
this was very helpful and straight forward, thank u very much. the only obstacle I came across was that Django installation should be through pip3 not pip pip3 install django
instead of pip install django
Followed the tutorial, but when i try to run it in the browser I get ‘cannot connect to server… took too long to respond’ The server is up and running and I can pong the server ip no problem
I am facing two problems, please help me out.
1)I followed the steps given above for setting up, but when i try to run manage.py, I’m getting…
******(env) chaitanya@chaitanya-HP-Pavilion-Laptop-15-cc1xx:~/testsite$ python manage.py runserver Traceback (most recent call last): File “manage.py”, line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named ‘django’
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File “manage.py”, line 14, in <module> import django ModuleNotFoundError: No module named ‘django’
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File “manage.py”, line 17, in <module> "Couldn’t import Django. Are you sure it’s installed and " ImportError: Couldn’t import Django. Are you sure it’s installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Error in sys.excepthook: Traceback (most recent call last): File “/usr/lib/python3/dist-packages/apport_python_hook.py”, line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File “/usr/lib/python3/dist-packages/apport/init.py”, line 5, in <module> from apport.report import Report File “/usr/lib/python3/dist-packages/apport/report.py”, line 30, in <module> import apport.fileutils File “/usr/lib/python3/dist-packages/apport/fileutils.py”, line 23, in <module> from apport.packaging_impl import impl as packaging File “/usr/lib/python3/dist-packages/apport/packaging_impl.py”, line 23, in <module> import apt File “/usr/lib/python3/dist-packages/apt/init.py”, line 23, in <module> import apt_pkg ModuleNotFoundError: No module named ‘apt_pkg’
Original exception was: Traceback (most recent call last): File “manage.py”, line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named ‘django’
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File “manage.py”, line 14, in <module> import django ModuleNotFoundError: No module named ‘django’
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File “manage.py”, line 17, in <module> "Couldn’t import Django. Are you sure it’s installed and " ImportError: Couldn’t import Django. Are you sure it’s installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
Please help me out
Please verify that django is installed by running
django-admin version
as described above in Step 3 of the tutorial. If that doesn’t work, verify that you are in the environment in which you ranpip install django
. Which should be thevirtualenv
you’ve setup when following the tutorial.This comment has been deleted
Thank you sir! It worked. Regards, Krishna
I’m unable to start the server as shown above…
please help me
what is http://your-server-ip:8000/??
what is your server??? in the above line. my sysytem’s ip or 127.0.0.1? which of the following? how to know the my server ip? how to set up the server? please help me out!!!
Thanks and Regards, Krishna
Your
server ip
is the IP address for the server you’ve created. If you’ve created a droplet in DigitalOcean following the prerequisites of this tutorial you will have it displayed in your control panel. How are you logging into your server? You should be using the IP address when you ssh into it.You can also run the following command while you’re logged into your server, to get the IP address :
curl ipecho.net/plain ; echo
Thank you very much sir, Sir, i have used the above command to obtain my ip. what is the difference between python manage.py runserver and python manage.py runserver your-server-ip:8000
It is even working without specifying your sever ip, it is taking the default http://127.0.0.1:8000/
Thanks and Regards, Krishna
Thanks for your guide. I have a problem: i’m using an amazon EC2 server and when i try to run the server with my IP (i verified my ip also with
curl ipecho.net/plain ; echo
), i get this error:Thank you!
File “/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py”, line 50, in include urlconf_module = import_module(urlconf_module) File “/usr/lib/python2.7/importlib/init.py”, line 37, in import_module import(name) File “/home/dania/Trial/polls/urls.py”, line 1, in <module> from django.conf.urls import patterns,url ImportError: cannot import name patterns
<h1> I got errors like these can anyone help ?? </h1>
Great!! Thanks for your guidelines. It worked in one go!!!
i’m using an amazon Google Cloud Platform server and when i try to run the server with my IP (i verified my ip also with curl ipecho.net/plain ; echo), i get this error:
If using digital ocean firewalls - ensue to add ‘All TCP’ inbound rules (all ports) when running the server for the testtile Django file