Django Review Points
Tags: webdev, django, javascript, beginners
Published: 2023-04-04 12:29:45

## Settings file
### What is secret key?

A Secret key is a unique and random string of characters that is used for cryptograpic signing and to protect sensitive information in Django. It is used to sign cookies, CSRF tokens, and other secure data in Django.


### What are the default Django apps inside it? Are there more?

`django.contrib.admin` - provides a web-based admin interface for managing the application data.
`django.contrib.auth` - provides authentication functionality.
`django.contrib.contenttypes` - allows defining and managing content types for models.
`django.contrib.sessions` - provides session management functionality.
`django.contrib.messages` - provides a messaging framework for sending notifications and alerts to users.
`django.contrib.staticfiles` - provides a way to manage static files such as CSS, JavaScript, and images.
`django.contrib.sites` - provides a framework for managing multiple sites on a single Django installation.


### What is middleware? What are different kinds of middleware?

Read up a little on each security issue.**
Middlware is a set of components that sit between the web server and the view, and can perform various operations on requests/responses. It can be used for modifying requests/responses, authentication, caching and security.
Types of middleware:
- Process Request Middleware: It is called before view is executed and can be used to modify the incoming request, authenticate the user, or perform security checks.
- View Middleware: It is called after the view is executed and can be used to modify the response, perform additional authentication or authorization checks, or add additional data to the context.
- Template Response Middleware: It is called after the view has generated a response and can be used to modify the response before it is rendered by the template.
- Exception Middleware: It is called when an exception occurs during the request-response cycle and can be used to handle and log the exception, or display a custom error page.

Security issues:
- Cross-Site Scripting (XSS) Attacks: XSS attacks occur when a malicious user injects script code into a web page, which can then be executed by other users who visit the page. 
- Cross-Site Request Forgery (CSRF) Attacks: CSRF attacks occur when a malicious website sends a request to a site on behalf of an authenticated user, without the user's knowledge or consent.
- SQL Injection Attacks: SQL injection attacks occur when a malicious user injects SQL code into a database query, allowing them to access or modify data in the database.
- Authentication and Authorization Issues: Improperly implemented authentication and authorization systems can lead to security vulnerabilities such as password cracking, session hijacking, and privilege escalation.
- File Upload Security: File upload functionality can be vulnerable to security issues such as file tampering and file inclusion attacks.


### What is WSGI

WSGI stands for Web Server Gateway Interface. It's a specification for a universal interface between web servers and web applications or frameworks written in Python. The WSGI specification defines a set of rules and guidelines that enable Python web applications to communicate with web servers. 
WSGI allows web servers like Apache or Nginx to talk to Python web applications like Django or Flask. When a request comes into the web server, the server passes the request to the Python web application through the WSGI interface. The application processes the request and returns a response to the web server, which then sends the response back to the client that made the request.


## Models file
### What is ondelete Cascade?

on_delete=cascade is an option that can be specified when defining a ForeignKey field in a database model. It specifies what should happen when the referenced object in the ForeignKey relationship is deleted.
When on_delete=cascade is specified, it means that when the referenced object is deleted, all objects that have a ForeignKey to it will also be deleted. This behavior is called "cascade deletion".


### A broad understanding of Fields and Validators available to you

**Fields** are used to define the types of data that can be stored in a database model. Django provides a wide range of fields for different types of data, such as CharField for short strings, TextField for long text, IntegerField for integers, FloatField for floating-point numbers, BooleanField for true/false values, and many others.

**Validators** are used to validate user input in forms. Django provides several built-in validators for different types of data, such as EmailValidator for validating email addresses, MaxLengthValidator for enforcing maximum lengths on text fields, and MinValueValidator for enforcing minimum values on numeric fields. 


### Understanding the difference between Python module and Python class?

A module is a file that contains Python code, usually with a specific purpose or functionality. A module can define functions, classes, variables, and other objects that can be used by other programs or modules.

A class is a blueprint for creating objects that define a set of attributes and methods. A class is like a template or a factory for creating objects that share common characteristics and behaviors.


## Django ORM
### Using ORM queries in Django Shell

- Run the Django shell by typing python manage.py shell in the terminal.

- Once you're in the shell, you can import your Django models by typing from my_app.models import Car

- Retrieve all objects from a model
```{py}
all_objects = Car.objects.all()
```

- Retrieve a single object by its primary key
```{py}
single_object = Car.objects.get(pk=1)
```

- Filter objects based on specific criteria
```{py}
filtered_objects = Car.objects.filter(mileage=15)
```

- Update an object
```{py}
car.mileage = 20
car.save()
```

- Delete an object
```{py}
car.delete()
```


### Turning ORM to SQL in Django Shell

Every queryset object has query attribute, which holds the actual SQL query which will be sent to Database. query attribute return query when either print or convert it to str.
```{py}
q = MyModel.objects.all()
print(q.query)
```

### What are Aggregations?

Aggregations refer to the process of performing calculations across a set of related objects in the database.
Count - Returns the number of objects in a QuerySet.

Sum - Calculates the sum of values for a particular field in a QuerySet.

Avg - Calculates the average value for a particular field in a QuerySet.

Max - Returns the maximum value for a particular field in a QuerySet.

Min - Returns the minimum value for a particular field in a QuerySet.

StdDev - Calculates the standard deviation of a particular field in a QuerySet.

Variance - Calculates the variance of a particular field in a QuerySet.


### What are Annotations?

Annotations are used to add calculated fields to QuerySets that are not present in the database. Annotations allow you to perform complex calculations on related objects and add the results to the QuerySet as an additional field.

Annotations can be used with various aggregation functions and are a powerful tool for customizing the data returned by QuerySets. 

Use an aggregation function to calculate a value for an annotation:
```{py}
from django.db.models import Count

# Add a new field to the QuerySet that counts related objects
q = MyModel.objects.annotate(num_comments=Count('comments'))
```


### What is a migration file? Why is it needed?

A migration file is a Python file generated by Django's migration framework that describes changes to a database schema. Migration files are used to manage changes to database models and can be used to create or modify database tables, indexes, constraints, and other schema elements.
Some examples of operations that can be included in a migration file are:

- Creating a new table
- Adding a new column to an existing table
- Removing a column from an existing table
- Modifying a column in an existing table
- Creating or removing an index
- Creating or removing a constraint

Once you have created a migration file, you can apply the changes to the database using the migrate management command. This command reads the migration files in your project and applies the changes to the database schema in the correct order.


### What are SQL transactions? (non ORM concept)

- SQL transactions group a series of database operations into a single unit of work.
- Transactions are atomic, meaning they either succeed or fail as a single unit.
- Transactions must ensure that the database remains in a valid state before and after the transaction.
- Transactions are executed in isolation from other transactions to ensure consistency.
- Once a transaction is committed, its effects are permanent and cannot be undone.
- SQL transactions are used in applications that require reliable and consistent access to a database.


### What are atomic transactions?

- Atomic transactions are like a single unit of work, where a set of actions are either completed successfully all together, or none of them are executed at all. It's like a switch that turns all the lights on, or none of them, without leaving any halfway states.

- In Django's ORM, you can use the atomic decorator or context manager to support atomic transactions. When you wrap a block of code in an atomic block, it guarantees that either all the database operations within that block will succeed, or none of them will be executed at all. This helps to make your code robust and reliable.