DEV Community

Ravi Shankar
Ravi Shankar

Posted on

Django

Settings file

What is secret key?

The SECRET_KEY is a secret cryptographic key in Django that's used for secure hashing and cryptographic signing of sensitive data, such as cookies and sessions. It's a randomly-generated string that should be kept secret and never shared or exposed in your source code or version control. The SECRET_KEY helps protect against security vulnerabilities such as session hijacking and cross-site request forgery (CSRF).

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

Django includes several default apps, such as auth, admin, sessions, and messages. There are many more official Django apps available, such as cache, contenttypes, flatpages, and redirects, and you can also create your own custom apps as needed.

What is middleware? What are different kinds of middleware?

Middleware is a way to add extra functionality to the request/response processing flow in Django. Middleware sits between the web server and view layer and can modify requests, responses, or view processing.

There are different kinds of middleware, such as:

  • Security Middleware: adds extra security checks to your application, such as X-Content-Type-Options, X-XSS-Protection, and Strict-Transport-Security headers.
  • Session Middleware: provides session management for your application.
  • Authentication Middleware: handles user authentication and authorization.
  • Cache Middleware: caches responses to improve application performance.
  • CORS Middleware: adds Cross-Origin Resource Sharing support to your application to allow cross-domain requests.\

CSRF

CSRF (Cross-Site Request Forgery) is a type of web security vulnerability where an attacker can exploit a user's authenticated session to perform unauthorized actions on a web application. This type of attack is commonly performed by tricking the user into clicking on a malicious link or visiting a malicious website that contains a specially-crafted form that submits a request to the target web application.

To prevent CSRF attacks, Django provides built-in CSRF protection middleware that adds a CSRF token to all HTML forms and checks the token on form submissions. The CSRF token is a unique value that is generated for each user session and is stored in a cookie.

XSS

XSS (Cross-Site Scripting) is a type of web security vulnerability that allows attackers to inject malicious code into a web page viewed by other users.

XSS attacks can be performed by injecting code into input fields, URLs, or other parts of a web application that are not properly sanitized or validated.

To prevent XSS attacks, it's important to properly sanitize and validate all user input and output, and to use tools such as Django's built-in template escaping and the django-html-sanitizer package.

Click Jacking

Clickjacking is a type of web security vulnerability where an attacker tricks a user into clicking on a button or link on a web page that is actually hidden or transparent, causing the user to inadvertently perform an action that they did not intend to.

Clickjacking attacks can be performed by overlaying a transparent iframe on top of a legitimate button or link, or by using CSS to position a hidden button or link on top of a legitimate one.

To prevent clickjacking attacks, it's important to use the X-Frame-Options header to restrict the domains that can embed your website in an iframe.

What is WSGI?

WSGI (Web Server Gateway Interface) is a standard interface between web servers and Python web frameworks, such as Django, Flask, and Pyramid.

WSGI specifies how web servers should communicate with Python web applications and how web applications should respond to requests.

By conforming to the WSGI standard, Python web applications can be deployed on a variety of web servers, such as Apache, Nginx, and uWSGI, without requiring any modifications to the application code.

Models file

What is ondelete Cascade?

on_delete = CASCADE is a parameter in Django's ForeignKey field that specifies what should happen to the child objects when the referenced parent object is deleted.

When a ForeignKey is created with on_delete = CASCADE, it means that when the referenced parent object is deleted, all the child objects that have a foreign key to the parent object will also be deleted.

Understanding the difference between Python module and Python class?

In Python, a module is a file that contains Python code, such as functions, classes, and variables, that can be imported and used in other Python code. A module can be thought of as a collection of related code that serves a specific purpose.

On the other hand, a class is a blueprint for creating objects that defines a set of attributes and methods that the objects will have. A class can be thought of as a template or a user-defined data type.

In other words, a module is a way to organize and reuse code, while a class is a way to define and create objects with specific properties and behaviors. Modules can contain multiple classes, as well as other code, while a class is typically defined within a module or in a separate module.

Modules and classes are both important concepts in Python programming and are often used together to create complex and reusable code.

Django ORM

Using ORM queries in Django Shell

Start the Django shell by running the command python manage.py shell.
Once in the shell, you can import the model that you want to query,
for example:

from myapp.models import MyModel
Enter fullscreen mode Exit fullscreen mode

You can then perform ORM queries on the model using the standard Django query syntax. For example, to retrieve all objects of a model, you can use

MyModel.objects.all()
Enter fullscreen mode Exit fullscreen mode

Turning ORM to SQL in Django Shell

To turn ORM queries into SQL queries in the Django shell, you can use the query method of a QuerySet object. This method returns the raw SQL query that Django generates based on the ORM query.

Here's an example of how to do this:

  • Open the Django shell by running the command python manage.py shell.
  • Import the model you want to query, for example:
from myapp.models import MyModel
Enter fullscreen mode Exit fullscreen mode
  • Perform the ORM query on the model, for example:
queryset = MyModel.objects.filter(name='John')
Enter fullscreen mode Exit fullscreen mode
  • Call the query method on the QuerySet object to retrieve the SQL query, for example:
print(queryset.query)
Enter fullscreen mode Exit fullscreen mode
  • The SQL query will be printed to the console, allowing you to inspect it and analyze its performance.

What are Aggregations?

Aggregations in Django's ORM refer to the process of performing calculations on groups of objects in a QuerySet, such as calculating the average, count, sum, or maximum/minimum value of a field in the objects.

Django provides a number of built-in aggregation functions, such as Count, Sum, Avg, Max, and Min, which can be used in ORM queries to generate the desired result.

What are Annotations?

Annotations in Django's ORM refer to the process of adding extra information to each object in a QuerySet, such as calculating a value based on a related object or performing complex calculations on the fields of the object.

Django provides a number of built-in annotation functions, such as Count, Sum, Avg, Max, and Min, which can be used in ORM queries to generate the desired result.

What is a migration file? Why is it needed?

In Django, a migration file is a Python script that defines the changes to be made to a database schema, such as adding or removing tables, columns, or constraints.

Migration files are needed to manage database schema changes in a consistent and controlled way, ensuring that the changes are properly tracked, applied, and rolled back if necessary.

When you create a new model or modify an existing model in Django, you need to create a migration file to define the database changes associated with that model. You can then apply the migration file to your database using the manage.py migrate command, which updates the schema of your database to match the current state of your models.

What are SQL transactions? (non ORM concept)

SQL transactions are a set of one or more database operations that are performed as a single logical unit of work. A transaction is typically used to ensure that a set of related database operations are performed atomically, meaning that they are either all completed successfully, or all rolled back to their previous state if an error occurs.

What are atomic transactions?

Atomic transactions in Django's ORM refer to the concept of ensuring that a set of related database operations are performed as a single, indivisible unit of work. In other words, either all the operations are performed successfully, or none of them are performed at all.

In Django, you can use the transaction.atomic() decorator or context manager to wrap a set of database operations in an atomic transaction. This ensures that if any of the operations fail or encounter an error, the entire transaction is rolled back, and the database is returned to its previous state.

References

Top comments (0)