DEV Community

Vincent Tommi
Vincent Tommi

Posted on

Django Interview Questions & Key Concepts – Part 4

1 what are signals in Django?
Is a mechanism that allows different parts of a software to communicate in loosely coupled manner.
signals follow a publisher-subscriber pattern with signal senders acting as publishers and receivers as subscribers.

Types of signals
1 Model signal:
Django model signals are a way to decouple applications by allowing certain senders to notify a set of receivers when certain actions occur. These signals are dispatched at various points in the lifecycle of a model, such as before or after saving, deleting, or initializing an instance.

Some of the built-in Django model signals include:

pre_init and post_init: These signals are emitted at the beginning and end of the model's init() method.
pre_save and post_save: These signals are emitted at the beginning and end of the model's save() method.
pre_delete and post_delete: These signals are emitted at the beginning and end of the model's delete() method.
m2m_changed: This signal is emitted when a ManyToManyField is changed on a model instance.
class_prepared: This signal is emitted when a model has been defined and registered with Django's model system.

2 Response/Request Signal
n Django, request and response signals help decoupled components respond to events during the request/response cycle. The three main signals are request_started, request_finished, and got_request_exception.

request_started is triggered at the beginning of each HTTP request and is useful for logging or initializing resources, while request_finished is sent at the end of a request and often used for cleanup or metrics. However, these signals don’t provide the actual request or response objects—only the HttpRequest class as the sender—so middleware is a better option if access to those objects is needed. The got_request_exception signal is triggered when an exception occurs during request processing, allowing centralized exception handling.
3 Management Signals
In Django, management signals allow developers to perform custom actions during the execution of management commands. Signals like pre_command and post_command are triggered before and after a command runs, making them useful for tasks such as logging, validation, or modifying behavior. Similarly, pre_migrate and post_migrate are sent before and after database migrations, and can be used for tasks like data migration, setup, or cleanup operations. These signals help extend and customize the behavior of Django's management system.
4 Authentication signal
Authentication signals in Django are used to trigger specific actions during various stages of the authentication process. These signals can be useful for extending the functionality of the built-in authentication system or integrating with third-party packages like django-allauth. For instance, the user_signed_up signal is sent when a user signs up for an account, and it is typically followed by a user_logged_in signal unless email verification prevents the user from logging in.
Similarly, other signals such as password_set, password_changed, and password_reset are emitted during different stages of password management.

2 What is Media Root in Django?
n Django, MEDIA_ROOT and MEDIA_URL are settings used to handle user-uploaded content, often referred to as media files. These files can include images, documents, or any other type of content that users upload through forms or the admin panel.

To enable media file handling in your project, you first need to define the following in your settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Enter fullscreen mode Exit fullscreen mode

MEDIA_ROOT specifies the filesystem path on the server where uploaded media files will be stored. In this case, it's set to a folder named media within your project directory. This is where Django will save the files once they are uploaded.

MEDIA_URL defines the URL that serves these media files. When users or templates request a media file (e.g., an uploaded image), Django will use this URL as the base path.

For development purposes, you also need to configure your project to serve media files by adding the following to your urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # your URL patterns
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Enter fullscreen mode Exit fullscreen mode

This setup allows Django to serve uploaded files locally during development. In production, media files are typically served by a web server like Nginx or via cloud storage.

4 Explain the caching strategies of Django?
Django has its own inbuilt caching system that allows us to store our dynamic pages. So that we don't have to request them again when we need them. The advantage of the Django Cache framework is that it allows us to cache data such as templates or the entire site. Django provides four different types of caching options, they are:

per-site cache - It is the most straightforward to set up and caches your entire website.
per-view cache - Individual views can be cached using the per-view cache.
Template fragment caching allows you to cache only a portion of a template.
low-level cache API - It can manually set, retrieve, and maintain particular objects in the cache using the low-level cache API.

5 Types of model Inheritance styles in Django?
1 Abstract Base Classes:are used when the parent class contains common fields and the parent class table is not desirable. This style allows for code reuse without creating a separate database table for the parent class.
2 Multi-table Inheritance is used when the parent class has common fields, but the parent class table also exists in the database all by itself. This style creates a separate database table for each model in the inheritance hierarchy.
3 Proxy Models are used when you want to modify the behavior of the parent class, like by changing the order by or a new model manager. This style allows for altering the Python-level functionality of a model without changing its fields.

6 Exception classes present in Django?
Django provides several built-in exception classes to handle errors and exceptional situations during the execution of a web application. Some of the common exception classes in Django include:

django.core.exceptions.ObjectDoesNotExist: Raised when attempting to access an object that doesn't exist in the database.

django.core.exceptions.ValidationError:Used to collect validation error messages from forms.

django.core.exceptions.ImproperlyConfigured: Raised when the Django project or application is not configured correctly.

django.db.utils.IntegrityError: Raised when a database integrity constraint is violated.

django.core.exceptions.MultipleObjectsReturned: Raised when multiple objects are returned but only one was expected.

django.http.Http404: Raised to indicate that the requested resource could not be found.

AppRegistryNotReady:It occurs when the Django models are loaded before the Django app itself.

EmptyResultSet: Occurs when a query returns an empty set.

FieldDoesNotExist:
This occurs when a field does not exist in a model.

MultipleObjectsReturned: This occurs when a query returns more than one result.

SuspiciousOperation: This happens when the client does something suspicious for security reasons.

PermissionDenied: Occurs when the user tries to perform a task which he is not allowed to.

ViewDoesNotExist: Occurs when views do not exist.

MiddlewareNotUsed: This occurs when particular middleware is not used in the MIDDLEWARE section of settings.py.

FieldError
: Happens when there is an error in a model field.

ValidationError: Happens when data validation fails in forms or model forms.

Resolver404: Raised by the function resolve(), a part of Django.http.Http404 library. The exception occurs when path() does not have a valid view to map.

IntegrityError: This occurs when DB expects a value for a field but doesn’t get it from the user.

ServiceUnavailable: A custom exception class that can be used to indicate that the service is temporarily unavailable.

APIException: The base class for all exceptions raised inside an APIView class or @api_view.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.