Template directory in django and pass variable

Template directory in django and pass variable

By default, the Django template loader will look for a templates folder within each app. But to avoid namespace issues, you also need to repeat the app name in a folder below that before adding your template file.

Goto to settings.py

STATICFILES_DIRS = [
    BASE_DIR / "static",
]
( copy from here )
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "templates"],  (paste here this code  BASE_DIR / "templates"
        'APP_DIRS': True,

        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

( and paste here )

Create a templates folder at the route directory

templates/index.html

index.html

<p>hi this is template file {{variable2}}</p>

Goto to views.py because we have set all urls from views.py

views.py

from django.shortcuts import render, HttpResponse

# Create your views here.

def index(request):
    var = {
        'variable1':'this is variable1',
        'variable2':'this is variable2',
    }
    return render(request, 'index.html', var)

 

 

 

 

 

Leave a Reply