BlackWhite
BlackWhite

Reputation: 832

How render template from current app in django?

I have index.html in two places. One in /templates/index.html and another in /myapp/templates/index.html

In settings i have:

TEMPLATES = [
    dict(BACKEND='django.template.backends.django.DjangoTemplates', DIRS=[

        os.path.join(BASE_DIR, 'templates'),
        os.path.join(BASE_DIR, 'myapp/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',

        ]
    }),
]

in /settings.py

urlpatterns = [
    url(r'^myapp/(?P<param>\w+)/', include('myapp.urls', namespace='myapp',  app_name='myapp'), name='myapp'),
]

in myapp/urls.py

urlpatterns = [
    url(r'^$', views.test, name='test'),
]

in myapp/views.py

def test(request, param):

    response = TemplateResponse(request, 'index.html', {})

    return response

How can I get explicitly index.html from current app, not from root templates folder? I tried with

response = TemplateResponse(request, 'myapp/index.html', {})

but raise error : TemplateDoesNotExist

If I put os.path.join(BASE_DIR, 'templates') after os.path.join(BASE_DIR, 'room/templates') , work fine. No other way to prioritize search the template in project, depending on the current application, namespace etc?

Upvotes: 1

Views: 1798

Answers (1)

Louis Barranqueiro
Louis Barranqueiro

Reputation: 10238

Put your templates in templates/<app_name>/ or <app_name>/templates/<app_name>/. They will be automatically found by Django.

Django will look in the main templates folder templates/<app_name>/ and after <app_name>/templates/<app_name>/.

And then in your view :

response = TemplateResponse(request, '<app_name>/index.html', {})

Upvotes: 4

Related Questions