Django
Published: 2023-04-04 10:34:03

## Secret key

In Django, the secret key is a string of random characters used for cryptographic signing and protection against attacks such as session hijacking, cross-site request forgery, and other malicious activities.

In a new Django project, a secret key is automatically generated and stored in the settings.py file. The key is secret and it should not be shared with others, as anyone with access to it could potentially impersonate site users or modify data on the site.

A new secret key can be generated using django-secret-key or any other application.

It can be saved as an environment variable to prevent it from getting uploaded from the settings file through VCS. Cloud-specific tools can also be used to save it. Using separate settings files for development and production can also be done.

## Default Django apps

There are more apps than the default Django apps given in settings. They can be found in [src](https://github.com/django/django/tree/main/django/contrib). They are

- `django.contrib.admin`: Provides a web administrative interface for managing the Django project's data.
- `django.contrib.auth`: Provides user authentication and authorization mechanisms.
- `django.contrib.contenttypes`: Provides a framework for associating metadata with models.
- `django.contrib.sessions`: Provides session management functionality.
- `django.contrib.messages`: Provides a way to display one-time messages to users.
- `django.contrib.staticfiles`: Provides a framework for managing static files.
- `django.contrib.humanize`: Provides a set of template filters for humanizing data.
- `django.contrib.redirects`: Provides a way to redirect URLs.
- `django.contrib.sitemaps`: Provides a framework for generating sitemaps.
- `django.contrib.sites`: Provides a way to manage multiple sites using a single Django installation.
- `django.contrib.admindocs`: Provides a way to automatically generate documentation for the project's models.
- `django.contrib.postgres`: Provides support for PostgreSQL-specific functionality.
- `django.contrib.gis`: Provides support for geographic data.
- `django.contrib.syndication`: Provides a framework for generating RSS and Atom feeds.
- `django.contrib.webdesign`: Provides a set of template tags for generating dummy data.

## Middleware and different kinds of middleware

Middleware in Django is a component that sits between the web server and the view and provides a way to process requests and responses in a modular way. 

- Process Request Middleware: This middleware is executed at the beginning of the request cycle and can be used to perform tasks such as authentication, setting up the request, or modifying the request object.
- View Middleware: This middleware is executed just before the view function is called and can be used to modify the view's context or perform additional processing on the request.
- Template Middleware: This middleware is executed during the rendering of the template and can be used to add additional variables or processing to the template context.
- Process Response Middleware: This middleware is executed at the end of the request cycle and can be used to modify the response object or perform any final processing before the response is sent back to the client.

## CSRF

CSRF attacks let anyone use another person's website account without their permission. Django can stop this attack with its built-in protection. Django checks for a secret code in each form submission, so anyone needs to know the secret code to trick the website. This secret code is user-specific and stored in cookies. When using HTTPS, Django checks that the form is coming from the same place as the website. Using HTTPS helps make things more secure. The csrf_exempt decorator must be used only when it is necessary.

## XSS

XSS attacks are when someone injects harmful scripts into a website that can affect other people's browsers. Django templates can help stop these attacks. Django templates can protect against certain dangerous characters, but not all.

## ClickJacking

Clickjacking is when a bad website puts another website inside a frame, tricking people into doing things they didn't mean to do. Django has a way to protect against this called X-Frame-Options middleware, which can stop a website from being shown inside a frame in some browsers.

## WSGI

WSGI stands for Web Server Gateway Interface. It is a specification that defines how a web server communicates with a Python web application.

In Django, WSGI is used to allow a web server to interact with a Django application. It acts as a bridge between the two, allowing the webserver to send requests to the Django application and receive responses. The WSGI specification provides a standard interface for web servers and Python web applications to communicate with each other.

## Models

## ondelete

`on_delete` is a parameter that can be used when defining a foreign key relationship in Django models. It specifies what should happen when the referenced object is deleted.

`on_delete=CASCADE` is one of the options available for the on_delete parameter. It specifies that when the referenced object is deleted, all objects that have a foreign key relationship to it should also be deleted.

## Fields and Validators

A model field represents a database column and defines the type of data that can be stored in that column. Validators are functions that validate the data entered into a field according to some predefined rules.

## Module and Class

A module is a file containing Python code that can be imported and used in other Python files or modules. A module can contain functions, variables, classes, and other objects. A class is a blueprint for creating objects that define a set of properties and methods that the objects will have.

## Django ORM in shell

Django's Object-Relational Mapping (ORM) provides functionality to interact with a database using Python code instead of SQL queries. To use it in the shell import the model in the shell and use ORM functions on it.

## ORM to SQL in Django shell

The ORM can be converted into SQL using `.query` from the queryset.

```python
queryset = random_name.objects.filter(random_val=10)
print(queryset.query)
```

## Aggregation and Annotation

Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset. Aggregate are functions such as `Sum()`, `Avg()` etc.

## Migration file

A migration file is a script of instructions to modify the database schema. It is changed when a model is changed. It is needed to maintain schema in alignment with the models. `makemigrations` is used to generate the migration file and `migrate` is used to apply the changes to the database.

## SQL Transactions

SQL transactions are a way of grouping together a set of database operations so that they can be executed as a single atomic unit. A transaction allows the performing of multiple database operations as a single, consistent unit, either all succeeding or no change. It prevents incomplete execution of queries.

## Atomic transaction

Atomic transactions are used in Django to ensure all is completed or no change. It is the same as an SQL transaction. It is then done using SQL transactions depending upon the database used.