Sunday, 7 February 2016

Django on a Raspberry Pi 2 with Python 3.4

I've been following an old (3 yrs = old) post by Matt Woodward on setting up Django in a virtualenv on a Raspberry Pi...  but I keep seeing that Django now runs on Python 3.. and I prefer Python 3 on the Raspberry Pi... where possible.  So this is a follow-up tracing the steps I have taken to install Django in a Virtual Environment with Python 3 on the new Raspberry Pi 2.

After first trying it Matt's way, I wiped the RaPi2 and started over - easy to say with a Pi2 since it's much quicker than an old Pi...

The first step after reboot - and connecting to my Wifi... Is to update apt-get and upgrade the pre-installed packages, then do a Firmware update- which required a reboot.
sudo apt-get update
sudo apt-get upgrade
sudo rpi-update
Somewhere in the installation of Django with Python 2, I discovered I need python-dev... I tried apt-get install python3-dev and python3-setuptools... but they are already installed in the basic RaPi2 distro.  So is Nano.

Whilst looking up how to use virtualenv and virtualenvwrapper to create a Python3 environment, I discovered there's a native Python3 module that probably should be used instead, pyvenv.
sudo apt-get install python3-venv
Now I have two more commands:

  • pyvenv (should install the most recent Python version in the virtual environment)
  • pyvenv-3.4 (specifies Python 3.4)
Presuming you are in the folder where you would like to create virtual environments... we can now create a new Python 3.4 Virtual Env:
pyvenv-3.4 djenv
Unlike virtualenv, I can't use 'workon djenv' to activate it... we need to use 'source'
source djenv/bin/activate
Now I can see (djenv) added in front of the command prompt to indicate that I am working with the virtual environment, 'djenv'

pip is installed by default... so we can go right ahead and pip Django...
pip install Django==1.9.2  (taken from the DjangoProject download page
(The version might be different on the Django download page (it's now Feb 2016))

Some useful commands:
pip list = shows you which Python modules are loaded locally and their versions.  I installed Django outside of the environment and it is not available inside.  So I will run the above command inside the pyvenv.
pip show Django = shows you information about a package - here, Django.
Further reading on pip:

Then we're ready to create a new Django project:
django-admin startproject mysite
See the Django website for an excellent tutorial and documentation...

PS.  where the command calls for 'python'... I have been using 'python3' on the Raspberry Pi 2... so there is no confusion.. it might not be necessary - e.g.
python3 migrate

No comments:

Post a Comment