Django Setup Tutorial

Published on May 29, 2023.

After several years of constant updates and improvements, the Django [/dʒængʊ/] web framework has proven to be one of the most powerful and useful frameworks for building Database — Driven web applications due to its MVC-style architecture. It has been argued that Django follows the MVT pattern but for simplicity's sake, I would refer to it as MVC.

Django Setup Tutorial

After several years of constant updates and improvements, the Django [/dʒængʊ/] web framework has proven to be one of the most powerful and useful frameworks for building Database — Driven web applications due to its MVC-style architecture. It has been argued that Django follows the MVT pattern but for simplicity sake i would refer to it as MVC. It’s also worthy to note that Django and it’s libraries are built upon the Python Programming Language hence some knowledge of python is needed .

Within this article which was inspired by the 2018 Google Code-In-Challenge I would be showing how to get started with Django and also explain the basic concepts and architecture of the Django Web Framework.

First we need to remember that Django is a Python Framework hence having Python on your machine is a basic step for running Django. We would be making a great use of the a terminal or a Command Prompt as we have it in windows

· Python Setup

We would download and install Python 3.6.7 from the official Python website

You can test your installation by opening your Command Prompt then type

Python

This should launch an interactive python shell

In order to begin with this Project, it is advised we to create and a virtual environment where we install all needed all extra dependencies using virtualenv

· Django Setup

We would be using a Python download manager known as PIP to install Django on our local machine. Other useful dependencies would be installed by default while the Django installation takes places via the CLI.

Type in “ Pip install Django ” into your command line .

· Project Setup

In order to create a new django project via the command line we need to type in

“ django-admin startproject djangopwa

This will create a new django-project containing all the default django configurations for your web app. We should have a project structure similar to this

After creating a project we then need to create a new app within the project using the

“django-admin createapp test” command via the terminal

We need to tell Django that we have a new app and we do this through the step below.

Open the settings.py and scroll down till you see INSTALLED APPs, it is an array containing other default apps so we can add our right away.

The basic difference between a Project and an app within django is that a Project refers to the entire collection of the whole web app, so it contains all the configurations for the app while an App is a small piece of the web app that has a specific purpose , several Apps make up a Django project. So we can only have one project but numerous Apps.

We can also test our newly created project by starting the django server with the “ python manage.py runserver ” command and then opening up the server address [ http://127.0.0.1:8000/ ]in our browser

Congratulations !! We have seen how to setup a working Django project, Let’s talk a bit about how Django operates.

Django uses the MVC style architecture for it’s operations . Let’s try understand what the MVC architecture means with the diagram below .

As we make progress in our study of Django we would come to understand the diagram better. However, let’ s try demonstrating this architecture in few examples.

· Model

Django uses an Object-Relational Mapper[ORM] by default, this is a very great feature for newbies who are not yet familiar with working with Queries . ‘The ORM is a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion’ . Also Django uses PostgreSQL by default but this can be changed from the settings.py. The ORM uses objects, classes e.t.c hence a little knowledge of OOP in python is required to with django’s ORM.

We work with our models from the models.py file which is found within the created app. Below is an example model called Coder

from django.db import models



class Coder(models.Model):
name = models.CharField(max_length=100)



language = models.CharField(max_length=30)



def __str__(self):
return self.name

From the first line we can see imported django.db [a python/django module]. Then we proceeded to make a class named Coder and passed in the model.models argument . We also created two columns called name and language, in django we must specify the data type hence we gave them a CharField type with a max_length of 100[hundred] characters and also 30 . Lastly, we created a function that converts the object into a string and returns the string. Simple right???

After making a model inorder to save it into our database we need to run “ Python manage.py makemigrations ” this would prepare the tables and columns and also give warnings incase an error was found in the model. To finally save it we need to run the “Python manage.py migrate ” command the finally migrate the model and save it into our desired database. You can open and inspect the database if you have the db manager e.g db browser for sqlite installed on your machine.

We can interact specially with Django’s ORM running the ““ Python manage.py shell ” via a Command line or terminal. We would try performing four basic django operations that would affect our database .

· Create — operation

Here is how we create a new object into our database

>>> from test.models import Coder
>>> Programmer.objects.create(author=Robot, title='Learning Django', )

Take special note of the create keyword. We have used it to create a new object via the cli with an author Field and also a title Field

· get — operation

Inorder to retrieve a record from our database we use the get method. Just as the name implies, it gets information from our database. We can also specify the information we want to get by adding parameters to our get method.

>>> from test.models import Coder
>>> Programmer.objects.get(author)
>>> <Programmer: Robot >

Above we used the get method to retrieve the author field and we got “Robot”. We also have other methods for retrieving information from the database such as filter.

· Delete — operation

Whenever we wish to remove a record from our database we can always make use of the delete method.

Also remember to specify the record you wish to delete else you would end up wiping your entire database.

>>> from test.models import Coder
>>> Programmer.objects.get(author).delete()

From the example above, First we use the get to retrieve that particular field and then we apply the delete method. Making use of Primary Key[pk] or I.d number when working with the delete method is more efficient in avoiding unintended deletes.

Quite a handful on django models. We also need to remember that we can access our models from the built in admin page by registering our model with the following codes from the admin.py file. Alot more can also be done using the ORM but this little examples should explain the few concepts.

from django.contrib import admin



from .models import Author



#Created Models



admin.site.register(Author)

Lets move on to the next pattern, enough time spent on our Models

· View

The view is the user interface and also everything that the user sees whenever the app is opened. The View is mostly made up of HTML codes which are displayed on the browser. The View is configured first from the urls.py found in the base project folder not the created app by setting the routes. An example code is written below

from django.contrib import admin



from django.urls import path, include



urlpatterns = [



path('admin/', admin.site.urls),



path( ' ' , include('test.urls')),



]

Above, we made all necessary imports then we create an array called urlpatterns, and also create the paths, the first path, then we create our path with two empty quotation marks that indicates this would be the default path that is shown whenever the app is opened.

Next is the urls.py inside our created app .

from django.urls import path



from . import views



urlpatterns = [



path( ‘ ’ , views.base, name=’base’ ),



]

No much explanation here as it is similar to the urls.py for the whole project. We only make reference to our views.py file from here within our path.

Next is the views.py inside our created app .

# Create your views here.



from django.shortcuts import render, redirect



— — — — — — — — →



def base(request):



return render(request, ‘default/base.html’, )

Our views.py just contains a function called base that takes in a request and renders a HTML page once the function is evoked from urls.py. Let’s quickly create a our HTML file. Within our file we create a Templates folder and then create a HTML file and name it index.html or base.html . Here we quickly create some html to test our whole setup so far.

<H1> Yuppie it’s working </H1>

Then we start up the server with the “python manage.py runserver ” command via our command line.

Let’s now open up the address [ http://127.0.0.1:8000/ ] on browser ..

Wow …. Our code was successful

Let’s not forget our last architecture which is the controller .

· Controller

Simply said, the Controller is the middleman that connects the view and model together, meaning that it is the one passing data from the model to the view.

Goodluck as you advance in your quest to master the Django web framework. With constant practice and learning you should be able to get an advanced knowledge of django in no distant time.