Inject request into functions
Long story short: * Django lets you call functions in templates, but you can't pass any parameters. * Sometimes you need to use the request object to perform certain tasks, such as determining whether the current user has permission to do something. * The recommended approach is to call functions that require parameters in the view, and then pass the results as variables in the context. This sometimes feels a bit overkill. * Creating a templatetag to call any function with any parameter will definitely break the intention for not letting functions to be called with parameters in templates. * So, what if we could tell django to inject the request into certain functions? That's what this decorator is for. For instance, suppose you have a model: class SomeModel(models.Model): ... def current_user_can_do_something(self, request): ...some logic here using request... You could use the decorator like this: class SomeModel(models.Model): ... @inject_request def current_user_can_do_something(self, request=None): ...some logic here using request... And in the template go straight to: {{ somemodel_instance.current_user_can_do_something }} So that the decorator would perform some operations to find the request in the frame tree and inject it if found. The assertions are intented to make sure things will work even if the request cannot be found, so that the coder may program defensively.
- templates
- request
- decorators