Oscar Mederos
Oscar Mederos

Reputation: 29803

Show a Form in my template base using Django

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

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

Upvotes: 7

Views: 1729

Answers (3)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

Yea, this is what template context processors are useful for. They allow you to pass a variable to all your templates without having to specify.

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 apps, or in the main directory if you prefer)

from my_forms import MySearchForm

def search_form(request):
return {
     'search_form' : MySearchForm()
}

Now you can use the {{ search_form }} in all of you templates

Upvotes: 16

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13486

Why not using a custom context processor?

Upvotes: 0

Bryce Siedschlaw
Bryce Siedschlaw

Reputation: 4226

You could make it into a filter that returns the form, assuming it's static. It would then look something like this:

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

Or something along those lines. You can also make it so it takes arguments if you needed it 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

Upvotes: 1

Related Questions