【问题标题】:django view render to template from another appdjango 视图从另一个应用程序渲染到模板
【发布时间】:2015-12-15 16:18:00
【问题描述】:

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

结构是

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

我的 views.py 文件位于当前应用程序中,并试图访问主应用程序中的模板(在 pages 子文件夹中)。

我将如何渲染它:

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

【问题讨论】:

  • 什么不起作用?很可能应该是pages/home.html
  • 你可以使用"pages/home.html",Django 会处理它

标签: python django


【解决方案1】:

首先,您很可能应该在 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/ 的每个应用程序目录中查找模板:

您只需提及将其视为根路径的模板路径,那么简单:

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

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

【讨论】:

  • 谢谢 - 没有意识到它像“pages/home.html”这么简单。我尝试过导入和各种奇怪的东西。
【解决方案2】:

在您要渲染的同一个应用程序中创建视图会更简单吗?

from mainapp.models import mainappmodel
def currentappview(request):
    all = mainappmodel.objects.all()
    return render(request, "pages/home.html", {'all': all})

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 2016-11-02
    • 2012-06-20
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多