Django Framework
Tags: webdev, django, programming, api
Published: 2023-06-15 13:00:36

### What is secret key?
- The Django secret key is used to provide cryptographic signing. This key is mostly used to sign session cookies. If one were to have this key, they would be able to modify the cookies sent by the application.
- How to create example:-
Go to python shell:-
	```
	 python manage.py shell
	  from django.core.management.utils import
	 get_random_secret_key

	secret_key = get_random_secret_key()
	print(secret_key) //output
	e+qpb)x^mjtdbr!gc8@81+drn6gz*r)in=pu0=j8s7o3b@m9$z
	```

  


### MVT Architecture
In Django, the MVT (Model-View-Template) architecture is a design pattern that separates the components of an application to handle different responsibilities. Here's an overview of the MVT architecture in Django:

1.  **Model**: The Model represents the data structure and handles the interactions with the database. It defines the data schema, relationships between different data entities, and provides methods for querying and manipulating the data. In Django, models are typically defined as Python classes that inherit from the `django.db.models.Model` class.
    
2.  **View**: The View defines the logic behind handling and processing user requests. It receives requests from the user, interacts with the appropriate models to retrieve or manipulate data, and prepares the necessary data to be rendered by the template. In Django, views are Python functions or classes that receive HTTP requests and return HTTP responses.
    
3.  **Template**: The Template represents the presentation layer and defines how the data should be rendered and displayed to the user. It uses HTML, along with Django's template language, to structure the content and dynamically insert data retrieved from the views. Templates can include variables, loops, conditionals, and other template tags to control the rendering process.
The flow of data in the MVT architecture follows this pattern: User Request -> URL Mapping -> View -> Model -> Template -> Response

### Setting File
Inside the `settings.py` file in a Django project, you'll find various configurations and settings that define the behavior and functionality of the project.

 Here are some key aspects commonly found in the `settings.py` file:
1.  **Debug mode**: The `DEBUG` setting controls whether the project runs in debug mode or not. Debug mode provides detailed error messages and tracebacks for easier debugging during development.
    
2.  **Allowed hosts**: The `ALLOWED_HOSTS` setting specifies the valid hosts/domain names that the Django project can serve. It is a security measure to prevent HTTP Host header attacks. You should specify the appropriate domain names or IP addresses here.
    
3.  **Database configuration**: The `DATABASES` setting defines the configuration details for connecting to the project's database. It includes the database engine, name, host, port, username, password, and other relevant options. Django supports various database backends such as SQLite, MySQL, PostgreSQL, etc.
    
4.  **Installed apps**: The `INSTALLED_APPS` setting lists the Django applications installed in the project. These apps may come with Django or be custom-built for the project. Django uses this setting to discover and include the necessary app-specific configurations and URLs.
    
5.  **Middleware**: The `MIDDLEWARE` setting specifies a list of middleware classes that Django applies to each request/response cycle. Middleware components can perform various tasks like authentication, session management, CSRF protection, and more. You can customize the order and add/remove middleware based on project requirements.
    
6.  **Static and media files**: The `STATIC_URL`, `STATIC_ROOT`, `STATICFILES_DIRS`, `MEDIA_URL`, and `MEDIA_ROOT` settings handle the configuration for serving and managing static files (e.g., CSS, JavaScript) and media files (e.g., user-uploaded images). These settings define the URLs, storage locations, and other related options.
    
7.  **Template configuration**: The `TEMPLATES` setting defines the configuration for template rendering in the project. It includes options like template engines, template directories, context processors, and other template-related settings.
    
8.  **Internationalization and localization**: The `LANGUAGE_CODE` and `TIME_ZONE` settings determine the default language and time zone for the project. Django supports multilingual websites and provides tools for internationalization (i18n) and localization (l10n).
    
9.  **Authentication and authorization**: The `AUTHENTICATION_BACKENDS`, `AUTH_USER_MODEL`, and other related settings handle user authentication and authorization. They define the authentication backends, the custom user model (if any), password hashing algorithms, login/logout URLs, and more.
    
10.  **Logging**: The `LOGGING` setting configures the logging behavior of the Django application. It defines loggers, handlers, formatters, and log levels to control how logs are captured, processed, and outputted.


### Application File
In a Django project, application files are components that encapsulate specific functionality and can be reused across different projects. Each application typically has its own set of files and directories that work together to provide a specific feature or functionality within the project. Here's an overview of the main files commonly found in a Django application:

1.  **models.py**: This file contains the definition of the application's data models using Django's Object-Relational Mapping (ORM) system. Models define the structure and behavior of database tables, allowing you to interact with data in a Pythonic way.
    
2.  **views.py**: The `views.py` file contains the view functions or classes that handle HTTP requests and generate responses. Views receive requests, interact with models and other components, and render templates or return JSON/XML responses.
    
3.  **urls.py**: The `urls.py` file defines the URL patterns or routes for the application. It maps specific URLs to corresponding view functions or classes, allowing you to specify how requests should be handled and which views should be invoked.
    
4.  **forms.py**: This file contains Django forms that handle data validation and rendering HTML forms. Forms define the fields, validation rules, and behavior of input forms used in the application. They can simplify form handling and data processing.
    
5.  **admin.py**: The `admin.py` file allows you to register models to be managed through Django's built-in administration interface. It lets you define how models are displayed, filtered, and edited in the admin interface, providing a convenient way to manage data.
    
6.  **tests.py**: This file holds the test cases for the application. Django encourages writing automated tests to ensure the correctness and reliability of the application's functionality. Test cases can be created to validate models, views, forms, and other components.
    
7.   **apps.py**: The `apps.py` file provides application-specific configuration. It allows you to define metadata for the application, specify application-level signals, and perform application-specific initialization tasks.
    
8.   **Template files**: It is not recommended to write html code inside python script (views.py file) because:
1) It reduces readability because Python code mixed with html code
2) No seperation of roles. Python developer has to concentrate on both python code and
HTML Code.
3) It does not promote reusability of code
We can overcome these problems by seperating html code into a seperate html file.This
html file is nothing but template.
From the Python file (views.py file) we can use these templates based on our
requirement
    
10.  **Static files**:  Up to this just we injected normal text data into template by using template tags.
- But sometimes our requirement is to insert static files like images,css files etc inside template file.
    
11.  **Migrations**: As the application's data models evolve, Django uses migrations to manage changes to the database schema. Migration files are automatically created and stored in a `migrations` directory within each application. They track and apply database schema changes.

### Project Files
1.  **settings.py**: The main settings file in a Django project. It contains configuration options that apply to the entire project, such as database settings, middleware, installed apps, static and media file paths, and more.
    
2.  **urls.py**: The URL configuration file that maps URL patterns to corresponding views. It determines how URLs are processed and which view function or class is invoked for a particular URL.
    
3.  **wsgi.py**: The WSGI (Web Server Gateway Interface) file that acts as the entry point for the WSGI server to interact with the Django application. It sets up the Django application's environment and provides a callable application object.
    
4.  **manage.py**: A command-line utility script used for various management tasks in a Django project. It allows you to run development server, create database tables, execute custom management commands, perform migrations, and more.


### CSRF
CSRF stands for Cross-Site Request Forgery. It is a type of attack where an attacker tricks a user into performing unintended actions on a website without their knowledge or consent. The attack takes advantage of the trust between the user's browser and the target website, exploiting the fact that the browser automatically includes any relevant authentication cookies in requests to the website.

Here's how a CSRF attack typically works:

1.  The attacker creates a malicious website or injects malicious code into a legitimate website.
2.  The user visits the malicious website or the compromised legitimate website while authenticated to the target website.
3.  The malicious website or code triggers a request to the target website on behalf of the user, using the user's authentication cookies.
4.  The target website receives the forged request, assuming it originated from the authenticated user, and performs the unintended action.
5.  The user's account or data on the target website may be compromised or modified without their knowledge.

To prevent CSRF attacks, web applications use CSRF protection mechanisms, with the most common method being the usage of CSRF tokens. CSRF tokens are random, unique tokens generated by the server and embedded in the web forms or requests of the application.

Here's how CSRF tokens work:

1.  When the user loads a form or logs in, the server generates a CSRF token and associates it with the user's session.
2.  The CSRF token is then embedded in the form as a hidden input field or included as a header in subsequent requests.
3.  When the user submits the form or performs an action, the server verifies that the received CSRF token matches the one associated with the user's session.
4.  If the CSRF token is valid and matches, the request is considered legitimate, and the action is performed. Otherwise, the request is rejected.

### ORM
Django's ORM (Object-Relational Mapping) is a powerful feature that allows developers to interact with the database using Python code and objects, rather than writing raw SQL queries.

Here are commonly used methods and operations provided by Django's ORM:

1.  `objects.all()`: Retrieve all objects of a model from the database.
2.  `objects.get(**kwargs)`: Retrieve a single object that matches the specified filter criteria.
3.  `objects.filter(**kwargs)`: Retrieve a QuerySet of objects that match the specified filter criteria.
4.  `objects.exclude(**kwargs)`: Exclude objects that match the specified filter criteria.
5.  `objects.create(**kwargs)`: Create a new object and save it to the database.
6.  `object.save()`: Save changes to an existing object to the database.
7.  `object.delete()`: Delete an object from the database.
8.  `objects.count()`: Count the number of objects that match the specified filter criteria.
9.  `objects.order_by(*fields)`: Sort the QuerySet by one or more fields.
10.  `objects.values(*fields)`: Retrieve a QuerySet of dictionaries containing specific fields' values.
11.  `objects.annotate(*args, **kwargs)`: Perform aggregations or annotate additional fields in the QuerySet.
12.  `object.field`: Access a specific field value of an object.
13.  `objects.distinct()`: Return a QuerySet with unique results.
14.  `objects.exists()`: Check if at least one object exists that matches the specified filter criteria.
15.  `objects.update(**kwargs)`: Update one or more fields of multiple objects in a single database query.
16.  `objects.bulk_create(obj_list)`: Create multiple objects in a single database query.
17.  `objects.select_related(*fields)`: Retrieve related objects in a single database query to optimize performance.
18.  `objects.defer(*fields)`: Delay loading of specified fields until they are accessed.
19.  `objects.only(*fields)`: Restrict the fields retrieved from the database to improve performance.
20.  `objects.values_list(*fields)`: Retrieve a QuerySet of tuples containing specific fields' values.
Examples:-
```
	# Import necessary Django modules
	import os
	import django

	# Set up Django environment
	os.environ.setdefault('DJANGO_SETTINGS_MODULE',  'your_project.settings')
	django.setup()

	# Import your Django models
	from your_app.models import Person

	# Create a new person
	person = Person(name='John Doe', age=30)
	person.save()

	# Retrieve all persons from the database
	persons = Person.objects.all()

	# Print the names and ages of all persons
	for person in persons:
	    print(person.name, person.age)

	# Filter persons based on age
	persons_filtered = Person.objects.filter(age__gt=25)

	# Print the names and ages of filtered persons
	for person in persons_filtered:
	    print(person.name, person.age)

	# Update a person's age
	person_to_update = Person.objects.get(name='John Doe')
	person_to_update.age = 35
	person_to_update.save()

	# Delete a person
	person_to_delete = Person.objects.get(name='John Doe')
	person_to_delete.delete()

```
### References
[GFG](https://www.geeksforgeeks.org/django-tutorial/)
[DOCUMENTATIONS](https://docs.djangoproject.com/en/4.2/)