Show a Form in my template base using Django

前端 未结 3 1372
一整个雨季
一整个雨季 2021-01-02 20:44

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

3条回答
  •  萌比男神i
    2021-01-02 20:59

    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

提交回复
热议问题