Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django view render to template from another app

Tags:

python

django

I'm trying to render to a template from another app but not sure how to import or if I should be importing with templates?

The structure is

project->
    main app->
       templates->
         pages->
           home.html
         account ->
    current app->
       views.py

my views.py file sits within the current app and is trying to access templates within the main app (in the pages subfolder).

How would I render to it:

def temp_view(request):
    ....
    return render(request, "home.html",context)
like image 442
Yunti Avatar asked Dec 15 '15 16:12

Yunti


1 Answers

At first you should have most probably configure your templates static path in settings.py with something similar to this

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
                'django.template.context_processors.i18n',
            ],
        },
    },
]

APP_DIRS=True means Django will look for templates in each app directory in your case main_app/ and current_app/:

you have simply to mention the template path considering this as root path, so simply:

def temp_view(request):
   ....
   return render(request, "pages/home.html",context)

Django will look under main_app/ directory to find the file pages/home.html

like image 116
Dhia Avatar answered Oct 25 '22 12:10

Dhia