概述:
您好,我正在尝试以上操作。我正在使用带有自定义模板的站点地图框架,将所有链接都放在xml文件中。它工作到一定程度。数据库中的所有对象和静态视图都能完美显示。
但是出于搜索引擎优化的原因,我想为静态文件夹中的某些图像添加一些原始xml。而且由于它们是静态的,因此不会保存到数据库中,因此我无法获取它们,或与不存在的对象相关联的任何特殊搜索词值。我的假设是我的picture_seo
变量存在文件路径问题。
这是到目前为止我所拥有的一个例子,也是我想要做的一个构想:
URLS.PY
from django.contrib.sitemaps import views as sitemap_views
from django.views.decorators.cache import cache_page
from .sitemaps import HighPrioritySitemap, LowPrioritySitemap
# picture_seo = 'picture_seo.html' # not working when I uncomment it
sitemaps = {
'high_priority': HighPrioritySitemap,
'low_priority': LowPrioritySitemap,
# 'picture_seo': picture_seo # I want this passed in too but can't figure out how
}
urlpatterns = [
path('sitemap.xml', cache_page(60*720)(sitemap_views.index), {'sitemaps': sitemaps}),
path('custom-sitemap-<section>.xml', cache_page(60*720)(sitemap_views.sitemap),
{'sitemaps': sitemaps,
'template_name': 'sitemap_test.html'
}, name='django.contrib.sitemaps.views.sitemap'),
]
目录结构:
...
manage.py
some-templates/
picture_seo.html # I read I should make an html file for this, but xml is in there
original_object_template.html # same as above, but I used a for loop, and it works fine for all Objects in database
project/
urls.py
...
我尝试的内容:
当我取消注释字典中的picture_seo
变量和键/值对时,我得到AttributeError at /sitemap.xml 'str' object has no attribute 'protocol'
。
然后将其注释掉,我转到mywebsite.com/sitemap.xml,获取所有站点地图文件的索引。他们去了...com/custom-sitemap-high_priority.xml
和...com/custom-sitemap-low_priority.xml
,依此类推,除了我想在字典中传递的picture_seo
原始xml之外,它工作得很好。
玩了几个小时,我注意到您可以添加任何字典键以传递到sitemaps
变量内的path()中,这就是为什么我试图将{{1 }}中的变量以显示原始xml。我还注意到,我可以将原始xml放在模板中,但是当我这样做时,会将相同的xml复制到每个索引中,而我只想要一次。所以我被卡住了。我最好的假设是我的文件路径错误,因为我正在尝试使用您在render()视图时使用的原则,例如picture_seo
编辑:今天我尝试使用os模块。我将以下内容添加到了urls.py
picture_seo = 'picture_seo.html'
当我在django shell中签入时,文件的路径是正确的。但这也不起作用。当它处于二分位数时,我仍然会得到相同的AttributeError。因此,然后我将所有内容都放在open()的picture_seo_path中,并在其中使用了.read()和.readlines(),但是它们都不起作用。
问题:
如何将我的原始xml文件传递到sitemaps变量中?