Skip to content

Instantly share code, notes, and snippets.

@harisibrahimkv
Last active September 18, 2023 06:26
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save harisibrahimkv/8279101 to your computer and use it in GitHub Desktop.
Save harisibrahimkv/8279101 to your computer and use it in GitHub Desktop.
Virtualenv, Django & PostgreSQL setup instructions for the Django beginner level workshop.

Setup (Linux)

Virtualenv

It is always recommened to use virtualenv while you are doing development. virtualenv lets you create isolated development environments. It will help you not to mixup dependencies when working on more than one project on your machine.

Installing virtualenv

  1. You can use pip

     $ sudo pip install virtualenv  
    
  2. You can use your system's package manager

     $ sudo apt-get install python-virtualenv
    

More info at the official virtualenv website.

Creating virtualenv

Go to the desired folder where you would like to create a virtual development environment. Create a virtualenv.

$ virtualenv some_name

This will give you the output

Installing distribute ........................................
    ..................................................................
    ..................................................................
    .................done.
Installing pip...............done. 

You will be able to see a folder called some_name in the current directory.

Activating virtualenv

$ source <path to virtualenv some_name>/bin/activate

This will change your prompt to something like

(some_name)haris@insanity:~/bangpypers/drafts $

You have successfully created a virtualenv and activated it, thereby isolating your dev environment.

Deactivating virtualenv

$ deactivate

This will remove the some_name within paranthesis from the front of your prompt.

Django

Installing Django

Since you already have virtualenv setup and running, it is time to install Django. The D is silent. Make sure you have your virtualenv activated before installing Django.

$ pip install django

Although it might take a while, this should give you an output which looks something like

Downloading/unpacking django
Downloading Django-1.6.1.tar.gz (6.6Mb): 6.6Mb downloaded
Running setup.py egg_info for package django

warning: no previously-included files matching '__pycache__' found under directory '*'
warning: no previously-included files matching '*.py[co]' found under directory '*'
Installing collected packages: django
  Running setup.py install for django
changing mode of build/scripts-2.7/django-admin.py from 664 to 775

warning: no previously-included files matching '__pycache__' found under directory '*'
warning: no previously-included files matching '*.py[co]' found under directory '*'
changing mode of /home/haris/bangpypers/drafts/venv/bin/django-admin.py to 775
Successfully installed django
Cleaning up...

Wonderful. You have successfully installed Django.

Starting a project

Django gives you a skeleton project structure to start with building your app. Go to the directory where you want to start the project and do

$ django-admin.py startproject my_awesome_website

No news is good news. This will give you a directory by the name of my_awesome_website within the directory that you executed the command from. The newly created directory will have the following structure:

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

We will cover what each means as we progress in the tutorial. However, let's see if this actually worked. Go inside your my_awesome_website directory and run

$ python manage.py runserver

You should see the following output

Validating models...

0 errors found
January 05, 2014 - 15:50:53
Django version 1.6, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Excellent! Head over to http://127.0.0.1:8000 in your web browser to be welcomed by the one and only... Django!

PostgreSQL

A web application is incomplete without a Database. Even though we could use something lightweight like SQLite, the best Django programmers recommend using postgreSQL. Hence, we will aim for the best.

Installing postgreSQL

Use your system's package manager

$ sudo apt-get install postgresql postgresql-client

This will not only install postgreSQL but also create a Database and its User with the name postgres by default.

For detailed installation instructions, please visit their wiki.

Creating a Database

Although this is enough and fine, let us create a database for our currently logged in user so that we know what is going on.

$ createdb awesome_db

Again, no news is great news. This will create a Database by the name awesome_db for the currently logged in user. If you do not specify the awesome_db in the above command, it will create a Database with the name same as that of the currently logged in user.

Manipulating the Database

In order to manipulate the postgreSQL Database, Users and Tables, you should use the psql command. You might find recommendations asking you to use pgadmin3. However, lesser the magic, the better. We will stick to psql.

$ psql

This will change your prompt to something like

haris=# 

Now, let us create a new user for our new Django project.

haris=# CREATE USER awesome_user WITH PASSWORD 'awesome_password';

Now to give this awesome_user permission to play with the awesome_db that we created earlier.

haris=# GRANT ALL ON DATABASE awesome_db TO awesome_user;

Excellent my friend! Let us move on and get Django connected to the awesome_db that we just created for the awesome_user that you are.

Django & PostgreSQL

Installing the adapter

Just like we use an adapter to make the Indian power plugs work on an American socket, we need an adapter to make Python work with PostgreSQL. The one we are going to use here is psycopg2. Yep, you read that right. Let us get that installed first.

$ pip install psycopg2

Good.

Configuring Django

The next thing to do is to tell Django about our adapter, our awesome database and its users. As you might have already guessed, we need to do this in the settings.py file within the my_awesome_website directory which is again within the top level my_awesome_website directory. Open it up.

You will see a lot of options. What you need to pay attention is to the DATABASES variable. Edit it in order to make it look like the following:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'awesome_db',
        'USER': 'awesome_user',
        'PASSWORD': 'awesome_password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

The fields are self explanatory. Even though the documentation says we can leave the HOST and PORT blank if we are running the postgreSQL Database on localhost, I ran into some trouble for doing that. You can read upon it here. So for the time being, mention 'localhost' for HOST.

Good job comrade! The configuration is complete. Let us move on to creating the necessary tables.

Creating Tables

As we will mention during the tutorial, there are a couple of pre-installed apps that Django comes with. These will require certain database tables for themselves. Let us see if our Database creation and configuration worked by creating the necessary tables for these apps. As intimidating as that sounds, it is easy to do. Run

$ python manage.py syncdb

If all is well, this should give you something similar to the following output:

Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'haris'): anyone_awesome     
Email address: anyone@awesome.com
Password: awesome_pass
Password (again): awesome_pass
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Go ahead and create the superuser when they prompt you for it above. Superusers are awesome.

Whoa! Excellent job my friend. Django Reinhardt would be proud of you. Well, not really, since we still haven't got to the guitar classes yet.

Soon soon!

@vibhorkashyap
Copy link

syncdb command is deprecated in django 1.7. Use the python manage.py migrate instead.

@martin-martin
Copy link

There's no need for psycopg2 anymore. In Django 2.0 the integrated postgresqlis enough and makes the setup even easier: https://docs.djangoproject.com/en/2.0/ref/settings/#databases

@martin-martin
Copy link

If you can't access psql or any db command, getting e.g. zsh: command not found: <your db command>, it is necessary to add Postgres to your PATH. This works by adding the below command e.g. to your .zshrc file (if using zsh):

# Add PostgreSQL path
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin

Then restart your shell, or type source .zshrc. Now the db commands and psql should work!

@rljhaines
Copy link

Does it matter if Postgres is installed while the virtual environment is active? Should databases be created, manipulated within the virtual environment?

@harisibrahimkv
Copy link
Author

@rljhaines No, it doesn't matter if Postgres is installed while the virtual environment is active or not.

Virtualenv being active or not only matters if you're accessing or manipulating the database via Django. That includes using the ORM and using the manage.py commands including the django shell.

@rljhaines
Copy link

That is a helpful explanation, thank you.

@Kiprotich-Code
Copy link

@harisibrahimkv Great explanation. Exactly what I was looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment