What is the difference between signal and middleware in Django?

Viewed 28

I dont understand what is the difference between this two function in Django.

Both is doing something before or after request/response.

Just like context switch or decorator.

Can anyone tell me how to use this two Django function properly.

1 Answers

According to Django documentation:

Signals:

Django includes a “signal dispatcher” which helps decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.

Middlewares:

Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output.

TLDR;

  • Signals are used to dispatch an information that will be listened by receivers, for example executing some code before saving something into the database or execute some code after an email was sent.
  • Middlewares are classes that hook into HTTP request/responses.
Related