【问题标题】:Django template decoupling : cant access to the static files outside of Django projectDjango 模板解耦:无法访问 Django 项目之外的静态文件
【发布时间】:2020-02-04 08:09:53
【问题描述】:

我的应用在 API 和模板之间解耦。我想知道将 API 与模板通信的方式。

我知道我可以通过 python manage.py collectstatic 将所有静态文件拉入 API 存储库,但我不想将 API 和模板结合到一个文件夹中。

我正在尝试从我的 django 应用程序访问静态文件到我的 django 应用程序之外的静态文件。我想将 UIUX/static 中的文件访问到 DjangoRepo/myapp/static。如下所示

UIUX/
 - static
  - staticfile...
 - templates
  - index.html
DjangoRepo/
 - myapp
  - static
  - templates

我的观点.py

class IndexViewTemplateView(View):
    # trying to acess the inedx.html file that is outside of Django file
    template_name = '../../../UIUX/templates/index.html'

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name)

    def post(self, request, *args, **kwargs):
        return render(request, self.template_name)

我根本没有为此编辑我的模板。 我需要做任何其他模板设置来存档吗?

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(PROJECT_ROOT, 'templates')],
        # 'DIRS':[],
        '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',
            ],
            # 'debug': DEBUG,
        },
    },
]

【问题讨论】:

    标签: python django django-templates django-views


    【解决方案1】:

    改变这一行 来自 - 'DIRS': [os.path.join(PROJECT_ROOT, 'templates')], to - 'DIRS': [os.path.join(PROJECT_ROOT,'templates'),os.path.join('C:/Users/kevin/workspace/UIUX/static')]。

    【讨论】:

    • os.path 模块始终是适用于 Python 运行的操作系统的路径模块,因此可用于本地路径。 join - 连接一个或多个路径组件。使用它我们可以调用本地目录文件。
    【解决方案2】:

    让我知道您的 PROJECT_ROOT 和 STATICFILES_DIRS。

    【讨论】:

    • PROJECT_ROOT = os.path.dirname(os.path.abspath(file))
    • STATICFILES_DIRS = (#os.path.join(PROJECT_ROOT, 'static/'), "C:/Users/kevin/workspace/UIUX/static", )
    • 您想要获取模板中的文件还是静态文件?
    • 两者。我想访问可以访问静态文件的模板
    • 对于静态文件,您可以使用“python manage.py collectstatic”。使用模板目录,您可以对其进行硬路径。试试看。
    猜你喜欢
    • 2021-03-11
    • 2020-11-26
    • 2013-10-01
    • 2018-08-31
    • 2020-10-02
    • 2022-11-30
    • 2013-06-18
    • 1970-01-01
    • 2014-05-23
    相关资源
    最近更新 更多