In this discussion, I am excited to introduce you to Django - a powerful Python backend framework used in web application development. Django is one of many server-side languages and frameworks available, but it stands out for its versatility and scalability.
It's important to note that Django is built on top of Python, a well-known programming language. With Django, developers can configure the server side of web applications used by companies such as Shopify, Google, Pinterest, and Instagram.
You might be surprised to learn that these major companies rely on Django for their backend operations. This framework is made even more accessible through its use of a Python package called pip, which is installed alongside Python.
Django allows developers to connect the server side of web applications with the user interface, using a variety of powerful concepts. Whether you're new to the framework or have some experience with it, this article will cover several important concepts to master. Join me on this journey to explore my favorite backend framework!
After reading this article, you will gain knowledge about the following topics:
Django project structure
How URL routing works in Django
The concept of MVT in Django
Understanding the Django Admin interface
Adding a custom database to a Django project
1. Django project structure
Let's begin by setting up the work directory for our Django project and creating a virtual environment. This is a crucial step in ensuring that all the necessary Django dependencies are installed using the Python pip command.
Type the following in the command prompt, remember to navigate to where you want to create your project:
The name of the virtual environment is your choice, in this tutorial we will call it world
.
For Windows:
py -m venv world
For Unix/MacOS:
python -m venv world
This will set up a virtual environment, and create a folder named "world" with subfolders and files, like this:
world
Include
Lib
Scripts
pyvenv.cfg
Then you have to activate the environment, by typing this command:
For Windows:
world\Scripts\activate.bat
For Unix/MacOS:
source world/bin/activate
Now, environment is activated.
So, It is advisable to install Python3
anyways. If you have no Python installed, then head on to official website and download the latest according to your OS.
To Check Python Version:python --version
Python 3.9.6
You are on the right track, keep reading…
Now Install Django in your virtual enviroment:
pip install django
You can verify this installation by freezing the requirements.txt
file.
$ pip freeze > requirements.txt
Let’s create our Django project now by running the command in terminaldjango-admin startproject dproject. (dproject is your projectname)
$ django-admin startproject dproject
Having succesfully created the dproject
, now run the command below and open the http://127.0.0.1:8000/
brought to you in the browser.
$ python manage.py runserver
2. URL routing in Django
URL routing is a critical aspect of Django web development. Essentially, URL routing maps the URLs entered by the user into the browser with the corresponding views. This communication happens back and forth between the client browser and the server.
Uniform Resource Locators (URLs) are addresses that allow clients to communicate with servers using HTTP requests. The server then renders any HTML file returned in the views that matches the route.
In Django apps, the URL routes are stored in a Python file named urls.py. This file contains essential features such as path, views, name, and URL pattern.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('users/', views.userList, name='users'),
]
3. Django Model View Template (MVT)
(MVT) is an acronym for MODEL VIEW TEMPLATE. Django as a web framework uses this architecture for its operation while other servers side language or framework use MODEL VIEW CONTROLLER, MVC. Let’s go over each keyword.
MODEL controls how the features and properties of the incoming data will look like. Developers describe the way data will be collected and saved in the database in this model.
from django.db import models
# Create your models here.
class Leads(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
contact = models.CharField(max_length=10)
def __str__(self):
return (f"{self.first_name} {self.last_name}")
What the private method __str__
does is that it helps to return whatever the firstname and lastname is as the representational name for our model in admin.
Now, migrate the model to create migration folder.
$ python manage.py makemigrations
Running this command, create a migration
folder inside the app. What this holds is just the required SQL commands for the model.
We can now migrate to the default database from Django Sqlite3
:
$ python manage.py migrate
Django has their own database called Sqlite3.
It's important to pay attention to the SQLite file created for your Django project.
In Django, Views are responsible for returning the rendered HTML template for each incoming URL request to a different route. These views are essentially Python functions or class-based views that render the template by returning data from the model after processing it.
The primary role of views is to accept data from models and map it to the appropriate HTML template file. Django uses the render method, which takes in three parameters: request, template_to_load, and context_dictionary.
Here's an example of a functional views.py file in a Django app:
from django.shortcuts import render
def myView(request):
context = {}
return render(request, index.html, context)
While this is the class based views in Django as well.
from django.views imoport TemplateView
class MyViewClass(TemplateView):
template_name = 'index.html'
- Note that class based views do not require
return
.
4. Django admin interface
Django helps developers by providing them a dashboard that contains all activities going on in the application and it is the admin
as the name implies. In the admin, all rows and columns of your model table made from models.py can be edited.
Admin is extended from django.contrib
Python module and for it to work as expected, one has to make a route for it in the project urls.py
and register it in the apps installed settings.py
.
Fortunately, this come default with django project created.
Now we have to register the models in admin.py
for accessing.
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
Then create a super user account that will access the admin and answer all questions about the credentials needed for the account.
$ python manage.py createsuperuser
Having done that, head on to the browser and paste the URL, then login to the account http://127.0.0.1:8000/admin
to view the admin prepared for your project.
5. Adding custom a database to a Django project
Django uses a relational database such as Sqlite3
which is the default development database. But in this section, I want to walk you through the mode of adding custom database of your choice.
We first need to download the type of database we will use and workbench into the machine. This can be done by doing a little research in Google.
Practical example can be found below where I used the postgresql
database.
Having downloaded and installed it, we can create a database name in the workbench and connect it.
Changing the following in the settings.py
file inside the dj-project
created earlier, will help your project utilize the database created.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'db_name',
'USER': 'db_user',
'PASSWORD': ********,
'HOST': 'localhost',
'PORT': '5432',
}
}
We will first run the command python
manage.py
makemigrations
to create SQL queries that will be used to create a table in the database.
To create a table in the database, we can run the python
manage.py
migrate
command.
To make migrations run:
python manage.py makemigrations
To apply the migrations run:
python manage.py migrate
Then you can go ahead and confirm the table with rows and columns created for your project in the postgres workbench.
Conclusion
In conclusion, Django is a powerful framework that simplifies backend web development. This article has provided a concise overview of key Django concepts. I encourage you to explore the official Django documentation for more information and reference it in your future projects. Congratulations on acquiring new skills!
Thank you for reading this article. Best of luck in your coding endeavors!
Happy coding!