Show form in my template database using Django

In the base template, I want to include a search form.

I already created it, but I wonder if there is a better option than passing form all my templates that extend the base?

+4
source share
3 answers

Yes, this is what template context processors are useful for. They allow you to pass a variable to all of your templates without specifying.

settings.py

 TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', ... 'some_app.context_processors.search_form', ) 

context_processors.py (you place this in one of your applications or in the main directory, if you want)

 from my_forms import MySearchForm def search_form(request): return { 'search_form' : MySearchForm() } 

Now you can use {{search_form }} in all your templates

+10
source

You can do this in a filter that returns a form, considering it static. Then it will look something like this:

 <body> ... {% import_form_template %} ... </body> 

Or something like that. You can also make it accept arguments if you need to be a bit more dynamic:

 {% import_form_template arg1 arg2 arg3 %} 

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

+1
source

Why not use a specialized context processor ?

0
source

All Articles