python – django视图从另一个应用程序渲染到模板

我正在尝试从另一个应用程序渲染到模板但不确定如何导入或者我是否应该使用模板导入?

结构是

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

我的views.py文件位于当前应用程序中,并且正在尝试访问主应用程序中的模板(在页面子文件夹中).

我将如何呈现它:

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

最佳答案 首先,您应该最有可能在settings.py中配置模板静态路径,其类似于此

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表示Django将在您的案例main_app /和current_app /中的每个app目录中查找模板:

你只需提一下模板路径,将其视为根路径,所以简单地说:

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

Django将在main_app /目录下查找文件pages / home.html

点赞