← back to blogposts

Django Setup 101: How To Fire Up Your Web Application

11/2020

If you are a Python or a web developer, you probably already know about Django: “The web framework for perfectionists with deadlines”. It is a great universal framework that provides tools to build a robust web app out of the box.

But before you can jump into the creative process of building your app, you have to set up everything first. And this can be tremendously annoying or tedious sometimes. Not to mention the situation, where you find yourself sitting in front of the computer saying “I should have done this in the very beginning.” 

I want to share some of these I-wish-I-knew-earlier things. Let's take it from the very beginning.

Goals

  1. Install python
  2. Choose virtual environment
  3. Set up a virtual environment
  4. Install Django
  5. Start a Django project
  6. Transfer to another database
  7. Create a custom User model

Prerequisites

1. Choose your Python version and install it

You should use the latest python version compatible with Django. You can always check the compatibility in the release notes.  

But be careful, as some python and Django packages take longer to be updated for brand new python versions. Check if the latest version is old enough. That means, if the version was released a week ago, start with the version before to avoid unpleasant issues.

2. Choose the virtual environment tool

Use virtual environments when coding in Python! Really. Thank me later. 

Anyway, there are multiple options when it comes to virtual environment tools. I will give you some of the most popular ones:

Venv

  • Venv is usually preinstalled with your python installation, you don't need to install it in advance. It is easy to use and simple.

Virtualenv

  • Virtualenv is pretty much the same as venv, but faster (venv is based on virtualenv). Plus tools like pip or wheel are usually more up-to-date and cached.

Pipenv

  • Pipenv is very popular among python developers. It's like Pipfile, pip and virtualenv had a baby (that.. would be strange). But it's pretty accurate. It aims to combine these three commands into one single command.

Conda

  • Conda offers much more than a simple environment management tool. It is actually a separate python ecosystem. It even has its own package repo, but you will find yourself using pip with conda pretty often, as conda contains about 1 % of PyPi packages. 
  • I personally use Miniconda, which is a lightweight version of Anaconda and contains some basic dependencies to give you a head start.
 
If you wish to know more, check this StackOverflow thread, for example. This tutorial will give you conda and virtualenv examples but if you choose to use another tool, it's completely fine.

Let’s get to it

1. Create the virtual environment and activate it

Conda:
$ conda create --name myproject python=3.8
$ conda activate myproject
 
Virtualenv:
$ virtualenv -p python3 myproject
$ source myproject/bin/activate
 
You should now see the name of your fresh environment in your command line.
(myproject) $

 

2. Install Django and start your project

Since you are using a virtual environment with python 3.x installed, you don’t have to type pip3, you can use pip.
(myproject) $ pip install django
 
Go to a directory where you want your project to live and run this command.
(myproject) $ django-admin startproject myproject
 
This will generate some initial folders and files important for your project:
myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
If that did not work, check Problems running django-admin.
 
Now try to simply start your development server:
(myproject) $ ./manage.py runserver
 
Let's take a closer look at this command. When you are in your virtual environment, you can use this in two ways:
 
Either
(myproject) $ python manage.py runserver
 
Or
(myproject) $ ./manage.py runserver
 
This can be done thanks to the first line in the file, which is called a shebang, it says what program should be used to interpret this file.
#!/usr/bin/env python
 
You are going to use the manage.py script to manage your web application from now on, so don't forget it!
 
After you hit enter, you should see something like this:
Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

November 12, 2020 - 15:50:53
Django version 3.1, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
 
Do not migrate for now, there is a good reason we haven't done it yet.
 
When you now navigate to 127.0.0.1:8000, it looks like this:
 
django rocket
 
So this means your development server is ready. Note the word development”. Do not use this on production, it was never meant to be a production environment. 
 
Now, before you start anything, think about how you are going to use your application and take a few things into consideration:
 
Is this just a training app you want to have only on your localhost and never go public? Well, then just stop right here and follow the official tutorial to make your first app.
 
But do you want to put your app to a production environment eventually? Maybe you will find these tips helpful:

 

3. Transfer to a database of your liking

Your project is connected to a default SQLite database right now. It is an easy solution that will help you learn the basics of Django, but it is not recommended for production. 
 
So choose your favourite database and connect it to your application before you make your first migrations. Here is an example of a widely-used and popular PostgreSQL:
 

1. Install the prerequisites

Ubuntu:
sudo apt-get update
sudo apt-get install libpq-dev postgresql postgresql-contrib
MacOS:
brew update
brew install postgresql

brew services start postgresql

pip3 install psycopg2-binary

 

2. Fire up the database console

Ubuntu:
sudo su - postgres
psql
MacOS:
psql postgres

 

3. Create the database

Of course, change ‘myprojectadmin' and 'password' to something you like.
CREATE DATABASE myproject;


CREATE USER myprojectadmin WITH PASSWORD 'password';


ALTER ROLE myprojectadmin SET client_encoding TO 'utf8';
ALTER ROLE myprojectadmin SET default_transaction_isolation TO 'read committed';
ALTER ROLE myprojectadmin SET timezone TO 'UTC';


GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectadmin;


ALTER USER myprojectadmin CREATEDB; # This has to be set in order for unit tests to work


\q 
exit # Only on Ubuntu - Exit from the postgres session

 

4. Configure your app for the new database

Go to myproject/myproject/settings.py. In there you can find the DATABASES dictionary:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
 
Go ahead and change it to this (use the credentials you used when you created the database):
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myproject',
        'USER': 'myprojectadmin',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}
 
We are done! but don’t run makemigrations yet and read the next part. Then you can finally make your initial migrations.

 

4. Create a custom User model

In case you want to have a good user system included in your application, set up a custom user model. Even if you don’t know yet. It may be helpful in the future, as it grants you the ability to change the user configuration, even on the run. 
 
What if you want the users to log in using their email or add some extra parameters? That would be impossible if you used the basic model. Have I convinced you? 
 
It is no hard task to do, follow this tutorial on testdriven.io. Michael Herman explained the whole process really well.
 
After you finish this, just make sure you ran
(myproject) $ ./manage.py makemigrations
(myproject) $ ./manage.py migrate
 
Go to 127.0.0.1:8000 to test if everything works as expected and start creating something amazing!
 
Thank you for reading! If you are interested in more tutorials, tips & tricks, or articles, check my blog again later, leave a comment/suggestion or follow my Instagram page to be sure you don't miss a thing:).



Add a comment
You can include your email if you want a response from the author.