在第三方Django应用中自定义模板 [英] Customize templates in a third party Django app

查看:45
本文介绍了在第三方Django应用中自定义模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django项目中使用了第三方应用程序(django-social-share),但是我需要自定义模板.我不确定该怎么做-我尝试的所有方法始终使用默认模板.

I'm using a third party app (django-social-share) in my Django project but I need to customize the templates. I'm not sure how to go about doing that--everything I try keeps using the default templates.

当前的默认模板存储在:

The current default template is stored in:

django-social-share/django_social_share/templates/django_social_share/templatetags/post_to_facebook.html. 

我在以下位置设置了自定义标签:

I've made my custom one in:

{{project_root}}/{{app_name}}/templates/django_social_share/templatetags/post_to_facebook.html

我的模板设置:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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.core.context_processors.request',
                'mainsite.context_processors.google_api'
            ],
            'loaders': (
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
                'django.template.loaders.eggs.Loader',
            ),
        },
    },
]

推荐答案

您可以将模板放在项目中的单独应用中.Django按照 INSTALLED_APPS 中定义的顺序在您的应用中查找模板,并使用第一个匹配项:

You can put the template in a separate app within your project. Django looks for templates in your apps in the order they are defined in INSTALLED_APPS, and uses the first match:

INSTALLED_APPS的顺序很重要!例如,如果您想要自定义Django管理员,您可以选择覆盖来自django.contrib.admin的标准admin/base_site.html模板,在myproject.polls中使用您自己的admin/base_site.html.那你必须确保您的myproject.polls在django.contrib.admin之前在INSTALLED_APPS中,否则将加载django.contrib.admin首先,您的将被忽略.()

因此,创建一个名为的应用,例如 social_share_templates ,然后将其放在 INSTALLED_APPS django_social_share 之前.然后将模板添加到此文件夹:

So create an app, called e.g. social_share_templates, and put it in INSTALLED_APPS before django_social_share. Then add the template to this folder:

{{project_root}}/social_share_templates/templates/django_social_share/templatetags/post_to_facebook.html

您当前的配置不起作用的原因是,您的本地应用与站点包中的应用具有相同的名称.如果您的本地应用程序是实际的python模块,则将无法在站点包中使用该应用程序.否则,Django只会在应用程序中的站点包中查找模板.

The reason your current configuration does not work, is that your local app has the same name as the app in site-packages. If your local app is an actual python module, you won't be able to use the app in site-packages. Otherwise, Django just looks for the templates in the app in site-packages.

这篇关于在第三方Django应用中自定义模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆