DEV Community

shiva yada
shiva yada

Posted on

Django

Settings file

1. What is secret key?

In Django, the SECRET_KEY setting is a value used for cryptographic signing and should be kept secret. It is used for various security purposes such as generating unique session IDs, creating CSRF tokens, and signing cookies. If an attacker gains access to your SECRET_KEY, they could potentially hijack user sessions or perform other malicious actions.

  • It is declared in settings.py

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

The default Django apps that come with a new Django project are:

  • django.contrib.admin : A built-in admin interface for managing Django models and data.

  • django.contrib.auth : A built-in authentication system for user management and authentication.

  • django.contrib.contenttypes : A framework for working with content types, which allows you to associate arbitrary data with models.

  • django.contrib.sessions : A framework for handling user sessions.

  • django.contrib.messages : A framework for displaying user messages, such as success or error messages.

  • django.contrib.staticfiles : A framework for managing static files, such as CSS and JavaScript files.

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

Middleware refers to a layer of software that sits between different applications or systems, facilitating communication and data exchange between them.

Different kinds of middleware:

  1. Application server middleware : This type of middleware provides a platform for developing, deploying, and running enterprise applications. Examples of application server middleware include JavaEE, Microsoft.NET.

  2. Message-oriented Middleware: This type of middleware enables different applications to communicate with each other through the exchange of messages. Examples of message-oriented middleware include IBM MQ and Apache Kafka.

  3. Database Middleware: This type of middleware provides an abstraction layer between applications and databases, allowing developers to work with databases using standard APIs. Examples of database middleware include JDBC and ODBC.

  4. Web Middleware: This type of middleware provides services that enable web-based applications to function properly. Examples of web middleware include Apache Tomcat and Microsoft IIS.

Common security issues with middleware include:

  1. Authentication and Authorization: Middleware is often used to manage authentication and authorization for applications, making it a prime target for attackers. If middleware is not properly secured, it can be vulnerable to attacks such as credential stuffing and brute force attacks.

  2. Data Leakage: Middleware can sometimes be configured to log sensitive data, such as user credentials, in clear text. This can leave the data vulnerable to interception by attackers.

  3. Injection Attacks: Middleware that handles user input, such as web middleware, can be vulnerable to injection attacks, such as SQL injection and cross-site scripting (XSS).

  4. Denial of Service: Middleware that is not properly configured or secured can be vulnerable to denial-of-service (DoS) attacks, which can bring down an entire application or system.

  5. CSRF ?

CSRF (Cross-Site Request Forgery) is a type of security vulnerability that allows an attacker to trick a user into unintentionally performing an action on a website without their knowledge or consent.

To protect against CSRF attacks, website owners can implement measures such as CSRF tokens, which are unique and random values that are included in each request and verified by the server to ensure that the request came from an authorized source.

6. XSS ?

Cross-site scripting (XSS) is a type of cyber attack where an attacker injects malicious code or scripts into a trusted website or application. They do this by sending a link to a user and tricking them into clicking it. If the website or application does not properly check the data it receives, the malicious code can execute on the user's system.

This allows the attacker to steal important information, such as the user's login details or session cookie. Essentially, an XSS attack can allow an attacker to take control of a website or application, and use it for their own purposes.

7. Click Jacking ?

Clickjacking is a type of cyber attack where an attacker tries to trick a user into clicking on something on a website or application that they did not intend to click on. This is usually done by overlaying a transparent or disguised element, such as a button or link, over a legitimate element on the website or application.

8. What is (WSGI)[https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface]?

WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request.

Models file

1. What is ondelete Cascade?

On delete cascade is used to automatically remove the matching records from the child table when we delete the rows from the parent table. It is a kind of referential action related to the foreign key.

2. A broad understanding of Fields and Validators available to you.

Fields: Fields are used to define the type of data that can be entered into a specific form element, such as text boxes, radio buttons, checkboxes, etc. The most common types of fields include:

Text fields: Used for entering text data, such as names, addresses, and descriptions.

Numeric fields: Used for entering numerical data, such as age, quantity, and price.

Date fields: Used for entering dates and times.

Boolean fields: Used for entering true/false or yes/no data.

File fields: Used for uploading files, such as images, documents, and videos.

Dropdown fields: Used for selecting one option from a list of options.

Validators: Validators are used to ensure that the data entered into a form element meets the required standards. Validators typically check for the following:

Required fields: Ensures that a specific field is not left blank.

Data format: Ensures that data is entered in the correct format, such as a valid email address, phone number, or credit card number.

Data range: Ensures that data falls within a specified range, such as a minimum and maximum value.
Data type: Ensures that data is of the correct data type, such as a number or text.
Custom validation: Allows developers to define their own validation rules based on their specific requirements.

Fields and validators play a critical role in ensuring that user data is accurate and consistent, reducing the risk of errors and data loss. By understanding how to use these tools effectively, developers can create more robust and reliable software applications.

3. Understanding the difference between Python module and Python class?

A module is a file with code that can be used in other programs. It can have functions, classes, and variables, and it's used to organize and reuse code.

A class is a blueprint for creating objects that have specific behaviors and attributes. It defines variables and functions that the object can have and use. Classes help make code more modular and reusable. While a module can contain multiple classes, a class cannot contain other classes, and it's usually defined within a module.

Django ORM

1. Using ORM queries in Django Shell

  1. Open your terminal and navigate to your Django project directory.

  2. Activate your virtual environment if you have one.

  3. Start the Django Shell by running the command python manage.py shell.

Creating Objects

To create a new object in your database using ORM queries, you can use the create method. For example, to create a new Person object with a name and age field, you can run:

from myapp.models import Person
person = Person.objects.create(name='John', age=25)
Enter fullscreen mode Exit fullscreen mode

Querying Objects

To query objects from your database using ORM queries, you can use the filter method. For example, to get all Person objects with an age greater than or equal to 18, you can run:

people = Person.objects.filter(age__gte=18)

Enter fullscreen mode Exit fullscreen mode

Updating Objects

To update objects in your database using ORM queries, you can use the update method. For example, to update the age field of all Person objects with a name of 'John', you can run:

Person.objects.filter(name='John').update(age=26)
Enter fullscreen mode Exit fullscreen mode

Deleting Objects

To delete objects from your database using ORM queries, you can use the delete method. For example, to delete all Person objects with an age less than 18, you can run:

Person.objects.filter(age__lt=18).delete()

Enter fullscreen mode Exit fullscreen mode

2. Turning ORM to SQL in Django Shell

In Django, you can convert ORM (Object-Relational Mapping) queries to SQL (Structured Query Language) queries in the Django shell using the query method on a queryset object.

  • Start the Django shell by running the command python manage.py shell in your terminal.

  • Import the model that you want to query by running from myapp.models import MyModel (replace myapp and MyModel with the appropriate app name and model name).

  • Get a queryset for the model by running qs = MyModel.objects.all().

  • Call the query method on the queryset to get the corresponding SQL query by running qs.query.

3. What are Aggregations?

Aggregations are a way to group and summarize data in a database or a data structure. In the context of databases, aggregations are often used to calculate statistics, such as averages, counts, sums, and maximum or minimum values.

In Python, aggregations are often performed using libraries such as NumPy or Pandas.

4. What are Annotations?

In Django, annotations allow you to add calculated fields to the queryset that are not part of the model definition. Annotations are useful when you need to perform calculations or add additional information to the queryset.

Annotations are created using the annotate method on the queryset. The annotate method takes one or more arguments, which are expressions that define the new field(s) to be added to the queryset. These expressions can be built using Django's query expression API, which provides a set of classes and functions for constructing complex database queries.

5. What is a migration file? Why is it needed?

Migration files in Django are Python files that contain instructions for updating the database schema to match changes in the model definition. They are generated automatically by the makemigrations command, which analyzes the models and creates a new migration file that represents the changes.

Migration files are needed because they provide a structured and repeatable way to modify the database schema without manually updating it. When you run the migrate command, Django reads the migration files and applies the changes to the database schema in the order they were created. This ensures that the database schema is always up-to-date with the latest model definition.

6. What are SQL transactions? (non ORM concept)

  • Atomicity: The entire transaction must be completed as a single, indivisible unit, or it must be completely rolled back to its previous state.
  • Consistency: The transaction must leave the database in a consistent state; in other words, all constraints must be satisfied.
  • Isolation: Transactions must be executed as if they are the only transaction executing on the database; concurrent transactions should not interfere with each other.
  • Durability: Once a transaction is committed, its changes are permanent and should be durable even if the system crashes or loses power.

7. What are atomic transactions?

Atomic transactions are a type of transaction in which all of the statements within the transaction are executed as a single, indivisible unit of work.

Atomic transactions are often used in database applications to ensure data integrity and consistency.

Top comments (0)