我正在尝试使用其内置框架 django-sitemaps 将站点地图添加到我的 Django 网站。我相信我已经根据(有时难以遵循)文档正确设置了所有内容,但是现在当我尝试时,runserver
我收到以下错误:
[...snip...]
File "E:\Programming\my_project\my_project\urls.py", line 7, in <module>
from sitemaps import StaticViewsSitemap
File "E:\Programming\my_project\some_app\sitemaps.py", line 2, in <module>
from models import Story
File "E:\Programming\my_project\some_app\models.py", line 18, in <module>
class Category(models.Model):
File "E:\Programming\my_project\venv\lib\site-packages\django\db\models\base.py", line 113, in __new__
raise RuntimeError(
RuntimeError: Model class models.Category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
有问题的模型some_app
绝对是其中的一部分INSTALLED_APPS
,它已经工作了几个月,我丝毫没有触及它,如果我注释掉与站点地图相关的所有内容,它就可以像现在一样完美地工作。该模型只是在 中声明的第一个模型models.py
。我认为该错误与导入和构建站点地图时未初始化项目的正确部分有关。
这是项目的目录树以及相关文件:
my_project
├ my_project
│ ├ ...
│ ├ urls.py
│ └ sitemaps.py
├ some_app
│ ├ ...
│ ├ models.py
│ ├ urls.py
│ └ sitemaps.py
├ some_app2
│ ├ ...
│ ├ models.py
│ ├ urls.py
│ └ sitemaps.py
└ some_app3
├ ...
├ models.py
├ urls.py
└ sitemaps.py
这是主要的url.py
:
from django.contrib.sitemaps import views
from sitemaps import StaticViewsSitemap
import some_app.sitemaps as some_app
import some_app2.sitemaps as some_app2
import some_app3.sitemaps as some_app3
sitemaps = {
"static": StaticViewsSitemap,
"some_app": some_app.sitemap,
"some_app2": some_app2.sitemap,
"some_app3": some_app3.sitemap,
}
sitemap_urls = [
path("sitemap.xml", views.index, {"sitemaps": sitemaps}),
path("sitemap-<section>.xml",
views.sitemap, {"sitemaps": sitemaps},
name="django.contrib.sitemaps.views.sitemap"),
]
urlpatterns = [
...,
*sitemap_urls,
]
my_project.sitemaps.py
:
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticViewsSitemap(Sitemap):
priority = 0.5
changefreq = "daily"
def items(self):
return [
"some_app:some_static_route",
"some_app2:other_static_route",
"some_app3:another_static_route",
]
def location(self, item):
return reverse(item) # NOTE: I also tried with reverse_lazy() to no avail
some_app.sitemaps.py
(其他都类似):
from django.contrib.sitemaps import GenericSitemap
from models import Story
sitemap = GenericSitemap(
{
"queryset": Story.objects.filter(draft=False, secret=False),
"date_field": "date",
},
protocol="https",
changefreq="weekly",
priority=0.7,
)
请注意,some_app.models.Category
任何站点地图都没有直接提到错误中的模型 ,它只是Story
. 即使我注释掉与 . 相关some_app
的任何内容,只要有任何内容从django.contrib.sitemaps
.
我可能遗漏了一些明显的东西,但我以前从未使用过 django-sitemaps,所以我不知道。我想我已经正确地遵循了文档。
我在 Django 版本 3.1.2 上。