问题描述
我想在 Django 的站点地图中添加 (/)。我使用以下代码在 django 中生成站点地图
我的 url.py 是
from django.contrib.sitemaps.views import sitemap
from myApp.sitemaps import staticSitemap,mySitemap
sitemaps = {
'staticSitemap':staticSitemap,'mySitemap':mySitemap
}
urlpatterns = [
path('admin/',admin.site.urls),path('sitemap.xml',sitemap,{'sitemaps': sitemaps} ),path('<slug:slug>/',apps.switcher,name='calc_detail'),]
from django.contrib.sitemaps import Sitemap
from django.shortcuts import reverse
from .models import SingleCalculator
class staticSitemap(Sitemap):
changefreq = "weekly"
priority = 0.9
def items(self):
return ['home','about','contact','privacy']
def location(self,item):
return reverse(item)
class mySitemap(Sitemap):
changefreq = "weekly"
priority = 0.7
def items(self):
return SingleCalculator.objects.all()
def lastmod(self,obj):
return obj.lastmod
<loc>https://sitename.com/absolute-difference-calculator</loc>
我想要 (/) 在 url 结尾之后。我该怎么做?
解决方法
在模型类 SingleCalculator 中添加 get_absolute_url 函数
def get_absolute_url(self):
return f'/{self.slug}/'