Reading Time: 13 minutes

Django on Raspberry Pi 3 with phpMyAdmin (Raspbian Stretch Lite, Apache, MariaDB and Python 3.x as the LAMP stack) – PART 1/3

Prep up the Pi

In a previous post, I installed Raspbian (Debian Stretch) using BerryBoot from an Android device on the Raspberry Pi 3B. We’ve in the past gone through the various use-case scenarios of the Raspberry Pi computers. In another previous post, I set up WordPress on a LAMP stack with MariaDB as a database and PHP 7.0 on the Raspberry Pi 3B. In this article, I’ll set up a Python (Django) web server on the same Raspberry Pi 3B that is already running a WordPress web server. I’ll use LAMP which is an acronym for – Linux, Apache, MariaDB, Python. I’ll also use phpMyAdmin which is a GUI administrative tool to easily manage MySQL and MariaDB database. Once I have everything in place, I will install Django on the web server and we’ll be ready to serve our custom websites from Raspberry Pi to any client. The Raspberry Pi being a small desktop computer, it is also easier to carry around if you want to showcase your Django based web projects to clients. But, keep in mind that with small architecture comes some restraints. Although it is a great tool to build custom web servers but using these web servers to serve a large amount of data to multiple clients can be quite a bad experience. Nonetheless, it has applications that are fulfilled by it the best.

For Linux, we’re using Raspbian (Debian Stretch) running on the Linux Kernel. I’ll install Apache2 as the HTTP web server that’ll help to serve dynamic web pages to clients connected to it. Since Django is a Python-based content management system (CMS) it needs a database to store data, for this I’ll be using MariaDB (Note:- By default, Django comes with a basic setup of SQLite database which we’ll be migrating to MariaDB). As the programming language – Python 3.x will be utilized.

I’ll go through the step-by-step installation and setup along with explanations for the steps taken. I’ll also show you some tips to make this setup robust and production-ready. SO, Let us Get Started!







Django as a CMS

Django is a free and open-source web framework, written in Python, which follows the model-view-template (MVT) architectural pattern. It is maintained by the Django Software Foundation, an independent organization established as a 501 non-profit. It is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. With Django, you can take Web applications from concept to launch in a matter of hours. Some of its features are:

Ridiculously fast – Django was designed to help developers take applications from concept to completion as quickly as possible.

Reassuringly secure – Django takes security seriously and helps developers avoid many common security mistakes.

Exceedingly scalable – Some of the busiest sites on the Web leverage Django’s ability to quickly and flexibly scale.

Fully Loaded – Django includes dozens of extras you can use to handle common Web development tasks. Django takes care of user authentication, content administration, sitemaps, RSS feeds, and many more tasks — right out of the box.

Incredibly Versatile – Companies, organizations, and governments have used Django to build all sorts of things — from content management systems to social networks to scientific computing platforms.







Apache HTTP web server

The Apache HTTP Server, colloquially called Apache, is free and open-source cross-platform web server software, released under the terms of Apache License 2.0. Apache is developed and maintained by an open community of developers under the auspices of the Apache Software Foundation.

Apache supports a variety of features, many implemented as compiled modules which extend the core functionality. These can range from server-side programming language support to authentication schemes. Some common language interfaces support Perl, Python, Tcl, and PHP. Popular authentication modules include mod_access, mod_auth, mod_digest, and mod_auth_digest, the successor to mod_digest.

A sample of other features include Secure Sockets Layer (SSL) and Transport Layer Security (TLS) support – (mod_ssl), a proxy module (mod_proxy), a URL rewriting module (mod_rewrite), custom log files (mod_log_config), and filtering support (mod_include and mod_ext_filter).

Popular compression methods on Apache include the external extension module, mod_gzip, implemented to help with reduction of the size (weight) of Web pages served over HTTP. ModSecurity is an open source intrusion detection and prevention engine for Web applications. Apache logs can be analyzed through a Web browser using free scripts, such as AWStats/W3Perl or Visitors.

Virtual hosting allows one Apache installation to serve many different Web sites. For example, one machine with one Apache installation could simultaneously serve www.example.com, www.example.org, test47.test-server.example.edu, etc.

Apache features configurable error messages, DBMS-based authentication databases, and content negotiation. It is also supported by several graphical user interfaces (GUIs).

It supports password authentication and digital certificate authentication. Because the source code is freely available, anyone can adapt the server for specific needs, and there is a large public library of Apache add-ons.







MariaDB as database

MariaDB is a community-developed fork of the MySQL relational database management system (RDBMS) intended to remain free under the GNU GPL. Development is led by some of the original developers of MySQL, who forked it due to concerns over its acquisition by Oracle Corporation. Contributors are required to share their copyright with the MariaDB Foundation.

MariaDB intends to maintain high compatibility with MySQL, ensuring a drop-in replacement capability with library binary equivalency and exact matching with MySQL APIs and commands. It includes the XtraDB storage engine for replacing InnoDB, as well as a new storage engine, Aria, that intends to be both a transactional and non-transactional engine perhaps even included in future versions of MySQL.

Its lead developer is Michael “Monty” Widenius, one of the founders of MySQL AB and the founder of Monty Program AB. On 16 January 2008, MySQL AB announced that it had agreed to be acquired by Sun Microsystems for approximately $1 billion. The acquisition completed on 26 February 2008. MariaDB is named after Monty’s younger daughter Maria, similar to how MySQL is named after his other daughter My.

MariaDB is used at Google, Mozilla and the Wikimedia Foundation.

Several Linux and BSD distributions include MariaDB, like Ubuntu (from 14.04 LTS). Some default to MariaDB, such as Arch Linux, Manjaro, Debian (from Debian 9), Fedora (from Fedora 19), Red Hat Enterprise Linux (from RHEL 7), CentOS (from CentOS 7), Mageia (from Mageia 2), openSUSE (from openSUSE 12.3 Dartmouth), SUSE Linux Enterprise Server (from SLES 12) and OpenBSD(from 5.7).







Python as the server-side scripting language

Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales. In July 2018, Van Rossum stepped down as the leader in the language community after 30 years.

Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library.

Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of Python’s other implementations. Python and CPython are managed by the non-profit Python Software Foundation.

Python is a multi-paradigm programming language. Object-oriented programming and structured programming are fully supported, and many of its features support functional programming and aspect-oriented programming (including by meta-programming and meta-objects (magic methods)). Many other paradigms are supported via extensions, including design by contract and logic programming.

Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. It also features dynamic name resolution (late binding), which binds method and variable names during program execution.

Python’s design offers some support for functional programming in the Lisp tradition. It has filter() , map() , and reduce() functions; list comprehensions, dictionaries, and sets; and generator expressions. The standard library has two modules (itertools and functools) that implement functional tools borrowed from Haskell and Standard ML.







The language’s core philosophy is summarized in the document The Zen of Python (PEP 20), which includes aphorisms such as:

Beautiful is better than ugly

Explicit is better than implicit

Simple is better than complex

Complex is better than complicated

Readability counts

Rather than having all of its functionality built into its core, Python was designed to be highly extensible. This compact modularity has made it particularly popular as a means of adding programmable interfaces to existing applications. Van Rossum’s vision of a small core language with a large standard library and easily extensible interpreter stemmed from his frustrations with ABC, which espoused the opposite approach.

While offering choice in coding methodology, the Python philosophy rejects exuberant syntax (such as that of Perl) in favor of a simpler, less-cluttered grammar. As Alex Martelli put it: “To describe something as ‘clever’ is not considered a compliment in the Python culture.” Python’s philosophy rejects the Perl “there is more than one way to do it“ approach to language design in favor of “there should be one—and preferably only one—obvious way to do it”.

Python’s developers strive to avoid premature optimization and reject patches to non-critical parts of CPython that would offer marginal increases in speed at the cost of clarity. When speed is important, a Python programmer can move time-critical functions to extension modules written in languages such as C, or use PyPy, a just-in-time (JIT) compiler. Cython is also available, which translates a Python script into C and makes direct C-level API calls into the Python interpreter.

An important goal of Python’s developers is keeping it fun to use. This is reflected in the language’s name—a tribute to the British comedy group Monty Python—and in occasionally playful approaches to tutorials and reference materials, such as examples that refer to spam and eggs (from a famous Monty Python sketch) instead of the standard foo and bar.

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language, that it conforms with Python’s minimalist philosophy and emphasis on readability. In contrast, code that is difficult to understand or reads like a rough transcription from another programming language is called unpythonic.

Users and admirers of Python, especially those considered knowledgeable or experienced, are often referred to as Pythonists, Pythonistas, and Pythoneers.







Hardware List to build my Raspberry Pi 3 Django server

I used the following hardware to build my Raspberry Pi web server:

Raspberry Pi Case (for Raspberry Pi 3 Model B only)

Raspberry Pi 3 Model B Motherboard

SanDisk Ultra MicroSDHC 16GB UHS-I Class 10 Memory Card with adapter

Xiaomi Mi 4 Charger – Original Adapter with USB cable( 5 Volts 2 Amperes)

Mini Keyboard Wireless Touchpad Keyboard With Mouse Combo

Raspberry Pi 3 board will load an operating system from a microSD card. Hence, we will need to have a computer with a SD card reader. If your computer does not come with a SD card reader (Buy from Amazon India), you have to get one.

Creating my Web server for Django







Quick Video Edition:









Step-by-step follow-along written guide:

Update System ->

Login to the Raspberry Pi using a display or headlessly via SSH/VNC. Make sure to connect to the internet via RJ45 Ethernet or onboard WiFi. Update & Upgrade all your packages from their repositories. Open a new terminal and do the following as a user:

Type “ sudo apt update ” [press enter] Type “ sudo apt upgrade ” [press enter]









Install Apache server on Raspberry Pi -> Further on, I recommend to install and configure the next steps as the root user. But you may choose to not do so. Lets install Apache 2 web server on Raspberry Pi with common packages. You can add extra packages you think you might need.

Type the command in the terminal :

apt install apache2 apache2-doc apache2-utils ” without the quotes [press enter]. Add “sudo” before the command if you aren’t logged in as the root user.



” without the quotes [press enter]. Add “sudo” before the command if you aren’t logged in as the root user. ifconfig ” and note down the IP address that the RPi has been assigned by my router. You’ll find the IPv4 address under ‘eth0’ if the Pi is connected to the network via an Ethernet port, or, you’ll find the IPv4 address under ‘wlan0’ if it’s connected to the network via WiFi. If possible, provide a static address to the RPi from the router so the assigned IP never changes. I have reserved the IP-192.168.0.101 for the WiFi adapter of the RPi, on my router’s DHCP reservation list.

To be able to setup and make Apache work properly, I need an IP address dedicated to the Pi. In the terminal window,I type “” and note down the IP address that the RPi has been assigned by my router. You’ll find the IPv4 address under ‘eth0’ if the Pi is connected to the network via an Ethernet port, or, you’ll find the IPv4 address under ‘wlan0’ if it’s connected to the network via WiFi. If possible, provide a static address to the RPi from the router so the assigned IP never changes. I have reserved the IP-192.168.0.101 for the WiFi adapter of the RPi, on my router’s DHCP reservation list.

Now, open the web browser on the RPi3 and navigate to the IP address you just noted down. Navigate by using the IP address as the URL. You’ll be greeted by Debian’s default Apache2 welcome page. If you see this page you can be rest assured that your Apache web server is up & running.





Installing & configuring MariaDB server and command line client on Raspbian Stretch -> With the new version of Raspbian, MariaDB is included in the official repositories. After I had gotten Apache & PHP on my Raspberry Pi, I then proceeded on to install MariaDB database server and command line client. Unlike my previous experience with installing mysql servers, this installation of mariadb-server did not prompt me for a root password . This was because the root user was by default set to use the unix_socket plugin, which allows the user to use operating system credentials when connecting to MariaDB via Unix socket.

If you’re using the terminal as another user other than the root user you’ll be prompted to enter a password for the MariaDB administrative root user.

To install MariaDB , type in the terminal:

“ apt install mariadb-server mariadb-client ” , [without quotes and press enter] and subsequently accept the installation prompt. The installer might show additional suggested packages which you can install after this installation is completed. You may choose not to install the suggested packages and continue with the steps as I’ve shown.

Since I prefer to have MariaDB prompt me for a password, I first got into the MariaDB interactive shell with the command “ mariadb “. * If you did enter a root password during setup then type “ mysql -u root -p ” [and press enter] * . Once inside the MariaDB monitor, I used the following commands to setup my administrative root user’s password :

“ use mysql; ” [without quotes, press enter]”

update user set password=PASSWORD(“new_password”), plugin = ‘ ‘ where User=’root’; ” [without double-quotes, press enter] *Replace new_password with your desired password*

“ flush privileges; ” [without quotes, press enter] USE ‘ q ‘ to quit the MariaDB monitor, once you’re done. mariadb use mysql; update user set password=PASSWORD("new_password"), plugin = ' ' where User='root'; flush privileges; q





Installing & configuring phpMyAdmin on Raspberry Pi with Apache and MariaDB server -> phpMyAdmin is not required but it will make our life easier by providing a GUI administrative tool, if we need to do any troubleshooting for MariaDB/MySQL Database server. apt install phpmyadmin ” [without quotes, press enter] and accept the installer prompt.



I type the command “” [without quotes, press enter] and accept the installer prompt. no ‘ and continue with the installation. I’m choosing ‘no’ in the 2nd step because I’ll setup my custom database for Django instead.



During the installation, phpMyAdmin will prompt for configuring it. In the first prompt select ‘Apache2’ as the webserver. In the second prompt it will asks if I want it to create a database automatically, I choose ‘‘ and continue with the installation. I’m choosing ‘no’ in the 2nd step because I’ll setup my custom database for Django instead.



Once the configuration of phpMyAdmin is completed, it showed me that PHP 7.0 FPM was not enabled by default to be used by apache2. It also mentioned some commands for me to execute in order to start the PHP7-FPM service. Follow the below images and enable the PHP7-FPM service before proceeding. Then restart the Apache server services.





Apache configuration for phpMyAdmin -> Now, I need to configure Apache to work with phpMyAdmin. To do so, I edit the file “/etc/apache2/apache2.conf” using the text editor ‘nano’, so the command I typed was:

” nano /etc/apache2/apache2.conf ” [press enter].

This will open the apache2 configuration file in the nano text editor on the terminal. At the end of this file, add the line:

Include /etc/phpmyadmin/apache.conf ” [use ‘ctrl+o’ to save & then ‘ctrl+x’ to exit the text editor nano] *Note – keyboard shortcuts will be different if you’re using another text editor other than nano* .

After saving & exiting, I type ” apache2 restart ” to restart.



” [use ‘ctrl+o’ to save & then ‘ctrl+x’ to exit the text editor nano] I now secure my MariaDB server so that it can be used in production environment. For this, I type the command “ mysql_secure_installation ” [without quotes, press enter] and follow the prompts to setup (Refer images). Remember to add “sudo” if using a non-root user.

chmod 755 /etc/phpmyadmin/apache.conf ” [without quotes, press enter]. Then restart apache2 service for the changes to take effect immediately without rebooting the RPi.

Once this has been done, I change permission settings for the file by using the command “” [without quotes, press enter]. Then restart apache2 service for the changes to take effect immediately without rebooting the RPi.





<IPAddress>/phpmyadmin/ “. This will open the administrative page and I can login with my administrative user ‘root’ and the password I set previously while configuring MariaDB.



Now, after having completed all the steps properly, I set out to test the phpMyAdmin installation. To do so, I open a browser window on the RPi and type ”“. This will open the administrative page and I can login with my administrative user ‘root’ and the password I set previously while configuring MariaDB.





Configuring and setting up Python and required dependency packages -> Open a terminal window and check for the Python versions installed on the Raspberry Pi. By default in recent versions of Raspbian, both Python 2.x and Python 3.x should be installed. Type “python -V” & “python3 -V” to check for them respectively.

If you want to default to a particular version of Python (2.x or 3.x), you can choose to set an alias for it. Here I have set my default python alias to python3 so that everytime I launch a python program with the command “python scriptname.py“, it uses Python 3.x by default. To do so, simply pass the command “alias python=python3”.

Now, we need to install some packages and in order to do so I type the command – ” sudo apt-get install python3-pip libapache2-mod-wsgi-py3 “. The ‘pip‘ package management system allows easy installation & management of Python packages. The other package mentioned here allows apache webserver to work efficiently with Python3. If you have read and followed my previous post on “WordPress, PHPMyAdmin on Raspberry Pi” you will remember that I installed a similar package called “mod-php” for php.

Now, using ‘pip‘ install ‘ virtalenv ‘. virtualenv is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. This allows you to isolate different Python programs/scripts into different environments without them conflicting with each other. To do so, type ” pip3 install virtualenv ” (add sudo before the command if you’re not using terminal as root user).









