Monthly Archives

July 2019

Create a Database Connected WebApp (Part I)

By | Django

In this post we will install MySQL connector for Python for getting started with Database connected Application on Django.

On MAC OS X, following additional steps need to be done for installing the Database connector, others can skip directly to Installing MySQL connector for Python.

First we need to install mysql-client on the system, so that the MySQL driver can be installed properly using pip. To do so, install homebrew if not installed. Once homebrew is installed, install mysql-client binary by using following command

brew install mysql-client

It will install mysql-client on your system. To make mysql-client available over terminal, add the following to your .zshrc or .bashrc file.

export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"
export PATH="/usr/local/opt/mysql-client/bin:$PATH"

Also add the following environment variable in your .zshrc or .bashrc file for SSL binary which get installed with mysql-client binary

export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"
export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"

Now restart your terminal, and you will be good to go.

Installing MySQL Connector for Python

Install MySQL Connector by passing following command to the terminal.

pip install mysqlclient

In second part, we will use mysqlclient package to connect our Application with the database.

Turn your First Project to Hello World!

By | Django

As we seen in last post, the application shows default Django page and not the "Hello World!" string. Isn't it sad?

In this post we will see how to create a "Hello World!" page inside Django application.

Step1: Create View

Create a new file named views.py inside HelloWorld directory and use this code :

 

Step2: Set the URL Pattern

Open the urls.py file and use this code :

 

Final Step: Run the server

python manage.py runserver 

 To terminate/stop the server, press CTRL+c key

Understanding Directory Structure

By | Django

HelloWorld/

This is our Django main project directory. It is just a container for our project hence we can rename this directory to anything.

HelloWorld/manage.py

manage.py is command line utility for interacting with your project.

HelloWorld/HelloWorld/

This is our project directory. It is the actual Python package for your project. 

HelloWorld/HelloWorld/__init__.py

An empty file, which guides Python to treat the directory as a Python module

HelloWorld/HelloWorld/settings.py

As the name suggests, this file contains configuration for the project. 

HelloWorld/HelloWorld/urls.py

This file contains URL pattern of the project.

HelloWorld/HelloWorld/wsgi.py

wsgi is Short for Web Server Gateway Interface. Hence this is the gateway file to wsgi-compatible servers or application. More about WSGI can be read here.