Complete Django Guide

I compiled this guide while learning Django myself. I tried to keep it relevant to people starting out to learn Django. From starting the very first dummy project to going deep into technicals.

You cannot go ahead and stat building things with Django if your PC has no installed version of Django. So, the very first step is installing Django in your PC. You can install it once and create Django projects without installing django ever again. But I will suggest you to create a virtual environment and install Django inside the virtual environment everytime you create a new Django project.

1. Install Django inside Virtual Environment

Python is a prerequisite for this task. If python is not installed in your system, first install python. Next run the command: py -m venv venv on a command-prompt window for creating a virtual environment. Next, execute the command: venv\scripts\activate to activate the virtual environment. Finally run: py -m pip install django to install Django inside the created virtual environment.

2. Setup your Django Project

Once you have activated a virtual environment and installed Django you are ready to create a project using django admin. Execute django-admin startproject your-project-name in a command-prompt window. It will create a folder named your-project-name in your current directory. So, before executing the command make sure you are in your preferred directory. A standard practice of django project directory looks like the tree below.

preferred-directory
│---venv
|---your-project-name

Development Server

To run the development server navigate to outer project folder and initiate the code

py manage.py runserver

Real Server

If you are running it in a real server do not use development server command. Instead go to the your sites file manager and open settings.py file in edit mode. Find ALLOWED_HOSTS = [] and edit it to ALLOWED_HOSTS = ['www.your-domain.com','your-domain.com']. Next,

Find passenger_wsgi.py and open in edit mode. Delete the existing codes and write the code given below

from your-project-name.wsgi import application

save it. Restart the python app and visit your-domain.com, it should show the django welcome page. Some servers take time. So, if you see any error message do wait for some time and if even then the error persist look out for solution.

App Creation

To create app inside your project navigate to the folder containg manage.py file and execute the code given below

py manage.py startapp appname

View Creation

A view in Django is a python function that takes a web request and returns a web response. Code example for creating a view under an app is given below


from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

View with Template

Templates are html files. Django lets you work on page designs separately from python code thats where templates come into play. Code for a simple home page with template is given below:


from django.shortcuts import render

def index(request):
	return render(request, "index.html", {})

Database Setup

By default django is configured with sqlite database. But for serious work we need to setup a good database system e.g. MySQL. Open settings.py file, search for DATABASES and write the given code below


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_database_name',
        'USER': 'your_user_name',
        'PASSWORD': 'your_password',
        'HOST': 'your_database_host', # usually HOST is localhost
        'PORT': 'port_number', # usually 3306 you can see it by opening phpmyadmin. Written next to localhost.
    }
}

Though the database credentials setup is done, you might face difficulty running migration. To overcome that you need to install mysql client with

pip install pymysql

Next open the project level __init.py__ file and write


import pymysql

pymysql.install_as_MySQLdb()

Now running the migration command

py manage.py migrate

will not result in any error message, provided above instructions are followed correctly.

Database Setup in CPnael

You might face difficulties installing mysqlclient package in cpanel shared hosting. To get around this problem install mysql-connector-python package instead. Use the command given below

pip install mysql-connector-python

After succesful installation, you need to create migration point by the command

python manage.py makemigrations

and finally run the migrate command to make changes in the MySQL database.

python manage.py migrate

Redirecting URL in Django

Open urls.py in project folder and add the below code.


from django.views.generic import RedirectView
urlpatterns += [
	path('', RedirectView.as_view(url='appfolder/', permanent=True)),
]