Django Framework
Published: 2023-06-15 12:46:25



### MVT Architecture


- **Django**, a Python framework to create web applications, is based on Model-View-Template (MVT) architecture.  **MVT**  is a software design pattern for developing a web application. It consists of the following three entities:
   1.  Model
   2.  View
   3.  Template

**Model**

- A  **Model**  is an object that defines the structure of the data in the Django application.

- It is responsible for maintaining the entire application’s data for which it provides various mechanisms to add, update, read and delete the data in the database.

**View**

- A  **View**  is a handler function that accepts HTTP requests, processes them, and returns the HTTP response.

- It retrieves the necessary data to fulfill the request using Models and renders them on the user interface using Templates.

- It can also create an HTML page using an HTML template dynamically, and populate it with data fetched from the model.

**Template**

- A  template  is a text file that defines the structure or layout of the user interface. The text file can be any type of file; for example HTML, XML, etc.

### Settings file

- **Secret Key**
	A secret key used for cryptographic signing and securing sessions, forms, and other sensitive data. It should be kept secret and unique for each project.
- **Debug Mode**
A boolean flag indicating whether the project is in debug mode or not. In debug mode. It's recommended to set `DEBUG = False` in production for security reasons.
- **Allowed Host**
A list of strings representing the host/domain names that the project can serve. It is a security measure to prevent HTTP Host header attacks. In production, you should specify the actual domain names or IP addresses that your project will be served from.
- **Database Configuration**
DATABASES: A dictionary containing the configuration settings for the project's database connections.You can specify the database engine, name, user credentials, host, and other database-specific settings.
- **Application configuration**
	-   INSTALLED_APPS: A list of Django applications installed in the project.
	-   Each application can define models, views, templates, and other components.
	-   Third-party applications are typically included by specifying their package 		   names.
	-   Your project's custom applications should also be included here.
	- In Django inside INSTALLED_APPS there are several default applicaition

		- `django.contrib.admin`: This app provides the Django admin interface, which allows you to manage and interact with your project's data models through a web-based interface.
    
		- `django.contrib.auth`: This app provides authentication and authorization functionality, including user authentication, permissions, and user management.
    
		- `django.contrib.contenttypes`: This app provides a framework for creating, storing, and retrieving content types. It is used by other apps to implement generic relationships between models.
    
		- `django.contrib.sessions`: This app manages user sessions and provides session-based data storage.
    
		-  `django.contrib.messages`: This app enables cookie- and session-based messaging between users and provides support for displaying success messages, error messages, etc.
    
		- `django.contrib.staticfiles`: This app helps manage static files (CSS, JavaScript, images etc) and serves them during development.
- **Middleware**
    - Middleware in Django is a component that sits between the web server and the view, providing a way to process requests and responses globally before they reach the view or after they leave the view. 
    - It allows you to add functionality to the request/response processing pipeline.

- **Django Security**
	 - Django is a well-known and widely used web framework that emphasizes security. 
	 - It provides a range of built-in security features and follows best practices to help developers build secure web applications.
- **Cross-Site Scripting (XSS) Protection**
    -   Django automatically escapes data rendered in templates, which helps prevent XSS attacks by default.
    -   Developers can also use the built-in template tags and filters, such as `|safe`, to mark specific content as safe from escaping.
- **Cross-Site Request Forgery (CSRF) Protection**
    -   Django provides CSRF protection by generating and validating CSRF tokens for all POST forms.
    -   The CSRF token is included in form submissions and verified on the server side to ensure that the request is legitimate.

- **User Authentication and Authorization**
    -   Django includes a robust authentication system that handles user registration, login, password hashing, and session management.
    -   It supports various authentication backends, including username/password, email/password, social authentication, and more.
    -   Django provides an authorization framework, including user roles, permissions, and groups, to control access to resources.
- **Password Hashing**
    -   Django uses strong cryptographic algorithms, such as PBKDF2, bcrypt, or Argon2, for password hashing.
    -   It automatically handles password salting and stretching to protect against brute-force attacks.

- **Clickjacking Protection**
	-  This type of attack occurs when a malicious site tricks a user into clicking on a concealed element of another site which they have loaded in a hidden frame or iframe.
    -   Django includes the `XFrameOptionsMiddleware` middleware, which sets the `X-Frame-Options` header to prevent clickjacking attacks.

- **WSGI**
	- WSGI stands for Web Server Gateway Interface. It is a specification that defines how web servers and web applications written in Python should communicate with each other. 
	- WSGI acts as a bridge between web servers (such as Apache or Nginx) and web applications (such as Django).
	- In the Django, WSGI is used to connect the Django web framework with a web server. 
	- It allows the web server to forward requests to Django and receive responses back. This enables Django to run as a standalone web application, handling HTTP requests and generating HTTP responses.


### Models file
- In Django's `models.py` file, you define the structure and behavior of your application's data using classes that inherit from Django's `Model` class. 
- These classes represent database tables, and the attributes of the classes define the fields and relationships of the corresponding database table columns.
-  In Django, `on_delete=Cascade` is a parameter used when defining a foreign key relationship between two models. It specifies what should happen when the referenced object (the object being referred to by the foreign key) is deleted.
- When `on_delete=Cascade` is specified, it means that if the referenced object is deleted, the objects that have a foreign key pointing to it will also be deleted (cascaded).
- Fields and Validators: In Django's models, we have a variety of fields and validators available to define the characteristics and constraints of your model's attributes.
- Some commonly used fields include `CharField` (for storing character strings), `IntegerField` (for storing integers), `DateField` (for storing dates), and `ForeignKey` (for establishing relationships with other models).

- Validators, on the other hand, are functions or classes that validate the values of model fields based on certain criteria. Django provides built-in validators such as `MaxValueValidator`, `MinValueValidator`, `EmailValidator`, and `RegexValidator`.
-  You can also create custom validators to enforce specific validation rules on your model's fields.

### Django ORM
- Django ORM (Object-Relational Mapping) is a powerful feature of Django that allows you to interact with your database using Python code instead of writing raw SQL queries.
- In the Django shell, you can execute ORM queries to interactively work with your Django models and perform database operations.
- run the folloing command to get into django shell
	```shell
	python manage.py shell
	```
## References

https://www.educative.io/answers/what-is-mvt-structure-in-django
https://docs.djangoproject.com/en/4.2/topics/http/middleware/
https://medium.com/scalereal/everything-you-need-to-know-about-middleware-in-django-2a3bd3853cd6
https://frontegg.com/blog/django-authentication