![]() |
VOOZH | about |
Django is a Python web framework used for building web applications quickly and efficiently. It provides a structured way to handle backend development with built-in support for common web features. It follows "batteries-included" approach, meaning most tools needed for web development are already available.
Django is based on MVT (Model-View-Template) architecture which has the following three parts:
For more information, refer to MVT Structure
A virtual environment is used to create an isolated workspace for a project. It allows each Django project to use its own dependencies and versions without affecting other projects or the system installation.
To create a virtual environment, the following command is used:
python3 -m venv venv
This creates a folder named venv that contains all the required files for the isolated Python environment.
To activate the environment, use the following command:
source venv/bin/activate
After you run the above command you should see (venv) at the starting of every line of your terminal as shown in the below image:
π python django virtual environment activate
To install Django, run the following command:
pip install django
For more information, refer to Django Introduction and Installation
A Django project is created using the built-in django-admin command. This generates the basic project structure required to start development.
This command creates a new folder named projectName containing all necessary Django configuration files.
django-admin startproject projectName
This moves into the project directory so that further commands can be executed.
cd projectName
python manage.py runserver
After running the server, the application becomes accessible at: http://127.0.0.1:8000/
For more information, refer to Create a Project using MVT
Django project is automatically created with a standard folder structure that contains configuration and control files required to run the application. These files handle everything from server management to routing, settings and deployment.
1. manage.py: used to interact with the Django project through the command line. It allows running the server, applying migrations and other administrative tasks.
python manage.py help
2. _init_.py: marks the directory as a Python package. It is executed when the package is imported and can be used for package initialization.
3. settings.py: contains all project configurations such as installed apps, database settings, middleware, static files, and more.
4. urls.py: defines URL routes for the project and maps URLs to their corresponding views.
5. wsgi.py: used for deploying the Django project. It acts as an entry point for web servers to communicate with the application using the WSGI standard.
An app is a self-contained module that handles a specific feature or functionality of a project. A single project can contain multiple apps, where each app works independently and focuses on one part of the system such as blog posts, authentication, or comments.
Django includes several default apps inside INSTALLED_APPS in settings.py:
These apps provide core functionalities such as authentication, sessions and admin interface.
To create a new app, the command is executed from the directory containing manage.py.
python manage.py startapp app_name
Now let's create an app called gfg_site_app, so the command to create the app would be:
python manage.py startapp gfg_site_app
Now you can see your directory structure as under :
π Creating app python django
After creating the app, it must be added to INSTALLED_APPS in settings.py so that Django recognizes it.
For more information, refer to Create an App
A view is a function or class that handles a web request and returns a web response. It acts as a bridge between the user request and the application logic, producing output such as HTML pages, redirects, error pages or any data that can be displayed in a browser.
π urlExplanation:
1. Function-Based Views (FBVs): are created using Python functions. They take an HttpRequest object as input and return an HttpResponse object. These views are commonly used for simple logic and CRUD operations. They are often used for:
2. Class-Based Views: are created using Python classes instead of functions. Each HTTP method (GET, POST, etc.) can be handled in separate class methods, making the code more structured and reusable. They are useful when:
URL patterns are used to map URLs to their corresponding view functions. This mapping is handled by a module called URLConf (URL configuration). Each request URL is matched against a list of patterns and when a match is found, the related view is executed to generate the response.
Hereβs a sample code for gfg_site/urls.py:
Explanation:
Each app can have its own urls.py file. These app-level URLs are included in the main projectβs URL configuration using include().
Example: Root URL Configuration
Explanation:
Now if head towards http://127.0.0.1:8000/ then our site will be:
In the above example, include statement will look into the URLpatterns list in the gfg_site_app/urls.py And then it will look into all the paths defined in the url.py file and will call the respective views function.
Django Models are used to define and manage the structure of database tables in a Django application. Each model represents a table and each attribute of the model represents a column in that table.
π databaseModels also provide a built-in ORM (Object Relational Mapper) that allows developers to create, read, update, and delete database records using Python code.
Syntax
from django.db import models
class ModelName(models.Model):
field_name = models.Field()
Explanation:
Example: Creating a Model
Explanation:
Whenever a model is created or modified, Django needs to update the database structure using migrations.
python manage.py makemigrations
python manage.py migrate
Explanation:
Django provides an ORM to interact with database data without writing SQL queries.
1. Creating Objects: To create an object of model Album and save it into the database, we need to write the following command:
Explanation:
2. Retrieving objects: To retrieve all the objects of a model, we write the following command:
Explanation: objects.all() returns all records from the table.
3. Modifying existing objects: We can modify an existing object as follows:
Explanation: get() fetches a specific record.
4. Deleting objects: To delete a single object, we need to write the following commands:
Explanation: delete() removes the record from the database.
Django allows image uploading using the ImageField in models. The upload_to parameter defines the folder structure where uploaded images are stored. A structured path such as images/%Y/%m/%d organizes files by year, month and date, making file management easier.
Before uploading images, Django must be configured to handle media files in settings.py.
Explanation:
To access uploaded files during development, Django must be configured in urls.py.
Explanation:
To render a model in Django admin, we need to modify app/admin.py. Go to admin.py in geeks_site_app and enter the following code. Import the corresponding model from models.py and register it to the admin interface.
Now let's create a superuser for our project that can have access to the admin area of our site. To create a super user type the below command:
python manage.py createsuperuser
Now go to http://127.0.0.1:8000/admin on the browser to access the admin interface panel.
π django admin interface login
Give the username and password created for superuser and then the admin dashboard will open and there we will be able to see our Geeks models that we just created.
Note: For more information refer to Render Model in Admin Interface.
Now let's see how to enter data using the admin dashboard. Now clicking on the Geeks Model we will see something like this:
π Django admin interface model
We can click on the Add Geeks Model button on the right top corner and then we will be able to see the fields for adding data:
π Django add data using admin
After adding the required data and the image field we will see something like this on our admin dashboard:
π django admin models dashboard
You can also see the media folder in your code editor:
Django comes built-in with the SQLite database. We can also see this in the DATABASES dictionary in our settings.py file.
If you want to change this to another database you can change the above dictionary. Suppose we want to change this database to PostgreSQL. Assuming the required dependencies are installed and the PostgreSQL is set up then the DATABASES dictionary will look like:
Template is basically written in HTML, CSS and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates.
π dajngo-templatesDjango Templates can be configured in app_name/settings.py,
Now let's create a template directory and add that directory in the above configuration. After creating the templates folder our directory should look like this:
π python templates directory
Let's add the location of this directory in our templates dictionary.
After adding the location of the template directory we will create a simple HTML file and name it as index.html and then we will render this file from our view function.
To render this HTML on our site we need to use the render function from the django.shortcuts. Below is the updated view function.
views.py
If we head to our website we will see the HTML data on our site as:
Let's see this with an example, where we will try to render the content of our database dynamically to our website. First, let's update our views.py file. In this file we will get our data from our database and then pass this database as a dictionary to our HTML file.
views.py
index.html
Our website now looks like this:
π passing context to django templates
Now if we add more data to our site then that data will also be shown to our site without making any changes to our HTML or views.py. Let's add some data and then see if it works or not.
π passing context to django templates
Django Template Language (DTL) is used to generate dynamic HTML pages in Django. It allows embedding Python-like logic inside HTML using variables, tags, filters, and comments. These elements help display data from views and control how content is rendered in templates.
1. Variables used to display dynamic data passed from the view into the template. Below is the syntax:
{{ variable_name }}
2. Tags: used to add logic inside templates such as loops, conditions, or content control. Below is the syntax:
{% tag_name %}
3. Filters: used to modify or transform variable values before displaying them. Below is the syntax:
{{ variable_name | filter_name }}
4. Comments: allow adding notes inside templates that are ignored during rendering. Below is the syntax:
{% comment %}
content
{% endcomment %}
Template inheritance allows one template to reuse the structure of another template using the extends tag. This helps avoid repeating common layout code. Below is the syntax:
{% extends 'template_name.html' %}
Child templates can override specific blocks defined in the base template.
Example: Paths in Template Inheritance
Django Forms are used to take input from users, validate the data, and process it before storing or using it in a database. They automatically map form fields to HTML inputs and provide built-in validation for secure and structured data handling.
A form is defined in forms.py inside the Django app.
Explanation:
The form is passed to a view using a context dictionary.
Explanation:
Map the view to a URL.
A form comes with 3 in-built methods that can be used to render Django form fields:
Now let's make the form.html for rendering our form.
Explanation:
After doing this save all the files and go to http://127.0.0.1:8000/add/ to see the form we created. It should look like this:
We can also see that our form is validated automatically. We cannot submit an empty form.
Django ModelForm is a class that is used to directly convert a model into a Django form. To create a form directly for our model, dive into forms.py and Enter the following -
Explanation:
views.py
Note: Add enctype= multipart/form-data to our <form> element in our template tag. If we don't have this then our request.FILES will always be empty and our form will not validate.
Let's add some data with our form and see if its get saved in our database or not.
After hitting submit the form gets saved automatically to database. We can verify it from the above GIF.