Django Basics
Tags: webdev, programming, interview, django
Published: 2023-06-16 12:29:02

# Django

## Introduction

A brief technical paper describing the workings of The Django framework.

**Pre-requisites:** Strong understanding of python. 

## The Settings File

- What is secret key?

    A secret key is an  important security setting used for cryptographic signing and hashing. It helps protect sensitive information, such as user passwords and session data. The secret key should be kept confidential and should not be shared publicly.

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

    You can find them listed in the `INSTALLED_APPS` setting in the project's settings module.

    `django.contrib.admin`: provides the Django administration interface, which allows you to manage your project's data through a web-based interface.

    `django.contrib.auth`:  handles user authentication and provides the necessary models, views, and forms for managing user accounts, passwords, and permissions.

    `django.contrib.contenttypes`:  provides a framework for creating, retrieving, and managing content types. It's used by other apps to associate models with permissions and generic relations.

    `django.contrib.sessions`: enables session management and allows you to store and retrieve session data for visitors.

    `django.contrib.messages`: provides a messaging framework that allows you to store messages for users and display them in a user-friendly way.

   `django.contrib.staticfiles`: handles static files (e.g., CSS, JavaScript, images) and collects them in a single location for deployment.

    In addition to these default apps, Django also includes other optional apps that you can choose to include based on your project's requirements. Some of these optional apps include:

    `django.contrib.gis`: This app adds geographic information system (GIS) support to Django, allowing you to work with spatial data.

    `django.contrib.postgres`: This app includes various features for working with PostgreSQL databases, such as advanced querying capabilities and specific model fields.

- What is middleware? What are different kinds of middleware? Read up a little on each security issue.

    Middleware in Django is a component that sits between the web server and the view function, allowing you to process requests and responses globally. It provides a way to modify or analyze HTTP requests and responses before they reach the view and after they leave the view, respectively

    Django provides several built-in middleware classes, and you can also create your own custom middleware. Here are some of the common types of middleware in Django:

    - `Authentication Middleware`: responsible for associating the user with the request by authenticating the user based on the provided credentials. It sets the request.user attribute, allowing you to identify the user making the request.

    - `Session Middleware`: manages the session data for each visitor and provides the ability to store and retrieve session variables. It enables you to maintain state across multiple requests.

    - `CSRF Middleware`: Cross Site Request Forgery middleware adds protection against CSRF attacks. It validates that the requests made to your site originate from your forms and protects against unauthorized form submissions.

    - `Security Middleware`: Django provides security middleware classes to enforce various security measures. Some of these classes include XFrameOptionsMiddleware (sets the X-Frame-Options header to prevent clickjacking attacks), ContentSecurityPolicyMiddleware (configures Content Security Policy headers), and SecureReferrerPolicyMiddleware (sets the Referrer-Policy header to control referrer information).

## Django Security

This is a set of measures implemented in Django, to protect web applications from various security threats and vulnerabilities. Here are some key aspects of Django security:

- CSRF protection

    Django provides built-in protection against CSRF attacks. CSRF attacks occur when an attacker tricks a user's browser into making unintended requests on a targeted website. Django includes a CSRF token mechanism that validates requests, ensuring they come from trusted sources.

- Cross Site scripting protection

    Django provides built-in protection against CSRF attacks. CSRF attacks occur when an attacker tricks a user's browser into making unintended requests on a targeted website. Django includes a CSRF token mechanism that validates requests, ensuring they come from trusted sources.

- Clickjacking protection

    Django includes measures to prevent clickjacking, where an attacker tricks a user into clicking on something malicious without their knowledge. Django supports setting X-Frame-Options headers to control framing of web pages, mitigating clickjacking risks.

## WSGI

The Web Server Gateway Interface is a simple calling convention for web servers to forward requests to web applications.

# Models

- ON DELETE CASCADE

    Cascade is used to define the behavior of related records when the referenced record in a parent table is deleted.

    `OnDelete` is one of the options available which specifies that if the parent element of the foreign key is deleted, all the related data should be deleted as well, this is done to maintain referential integrity.

- Fileds and Validators

    Fields and validators are integral parts of building and managing the database schema and data validation for web applications.

    **Fields:**

    Fields in Django represent the columns or attributes of database tables. They define the type of data that can be stored in a particular column and provide additional metadata about the data. Django offers a wide range of field types, including:

    `CharField`: Used for storing strings of a specific length.

    `IntegerField`: Stores integer values.

    `TextField`: Suitable for storing larger amounts of text.

    `BooleanField`: Represents boolean values (True/False).

    `DateTimeField`: Stores date and time information.

    `ForeignKey`: Establishes a relationship between tables, representing a one-to-many relationship.

    **Validators:**

    Validators in Django are functions or classes used to validate user input or data before it is stored in the database. They enforce specific constraints or rules on the data, ensuring its integrity and consistency. Django provides several built-in validators, example:

    `RequiredValidator:` Ensures that a field is not empty or null.

    `MaxValueValidator/MinValueValidator`: Validates that a numeric value is within specified maximum or minimum limits.

    `RegexValidator`: Validates that a field matches a specified regular expression pattern.

    `EmailValidator`: Verifies that an input string is a valid email address.

    `URLValidator`: Checks that a given string is a valid URL.

- Modules vs Classes

     A module in Python is a file that contains Python code, typically with a .py extension. It serves as a container for related functions, classes, and variables that can be reused in different parts of a program.

     A class in Python is a blueprint for creating objects. It is a code template that defines the attributes (data) and methods (functions) that an object of that class can have.

# Django ORM

- Using ORM queries in Django Shell

    You can use ORM queries within the django shell to experiment with data.

    - Activate the Django shell:

            python manage.py shell

    - Import necessary models:

            from utsav.models import Whatever

    - Perform queries:

            all_products = Product.objects.all()

- Turning ORM to SQL in Django Shell

    You can perform the ORM queries and convert them to SQL using the query method. Example:

            query = Product.objects.filter(price__gte=10).query

            sql=query.get_compiler(using=Product.objects.db).as_sql()

            print(sql)

- Aggregation

    Aggregation queries are equivalent to aggregate functions in SQL, they simply perform aggregation on all the records and return a singular value.

- Annotate

    Annotations are equivalent to group by statements in SQL, it is used to perform  aggregations on fields based on the same or other fields, For example: Getting the sum of total revenue generated by each employee, where we have a table consisting of each sale by employee.

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

    Migration file in Django is an autogenerated Python script that defines the changes to be made to the database schema

    Migrations enable version control of your database schema changes. Each migration file represents a specific set of changes to the schema, allowing you to track and revert changes if needed.

- What are SQL transactions?

    SQL transactions are units of work performed within a relational database management system. A transaction is a sequence of one or more SQL statements that are executed as a single logical unit. These statements can include queries, updates, inserts, and deletes.

- What are atomic transactions?

    If an error occurs during any step of the transaction, the changes made in the previous steps may or may not be rolled back, leaving the database in an inconsistent state.

    Atomic transactions ensure that all operations within a transaction are treated as a single unit, and they are either all successfully applied or none of them are. If any operation within the transaction fails, the changes made in all previous steps are automatically rolled back, maintaining data integrity and consistency.

# References 

[Geeks for Geeks](https://www.geeksforgeeks.org/django-basics/)

[Django Documentation](https://docs.djangoproject.com/en/4.2/)