From d1b41b37e48ab637675cd907219fe4964c4864aa Mon Sep 17 00:00:00 2001 From: Lacey Henschel Date: Wed, 29 May 2024 13:52:19 -0700 Subject: [PATCH] Create add_context_processor.md --- django/add_context_processor.md | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 django/add_context_processor.md diff --git a/django/add_context_processor.md b/django/add_context_processor.md new file mode 100644 index 0000000..11ffe9e --- /dev/null +++ b/django/add_context_processor.md @@ -0,0 +1,40 @@ +# Adding a custom context processor to your Django app so you can include bits of data in your template headers more easily + +## 1. Add `my_app/context_processors.py` + +```python +from __future__ import annotations + + +def my_context(request): + """ + Adds a special notice for a sale + """ + return {"notice": "All cat toys 50% off!"} + +``` + + +## 2. Add to settings + +In `settings.py`: + +```python +TEMPLATES = [ + { + ... + "OPTIONS": { + "context_processors": [ + ... + "my_app.context_processors.my_context", + ], + }, + } +] +``` + +## 3. Use your context value in your template: + +```html +

{{ notice }}

+```