如何在站点地图 Django 的 url 中添加尾部斜杠 (/)?

问题描述

我想在 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 中的 URL 一样

<loc>https://sitename.com/absolute-difference-calculator</loc>

我想要 (/) 在 url 结尾之后。我该怎么做?

解决方法

在模型类 SingleCalculator 中添加 get_absolute_url 函数

def get_absolute_url(self):
        return f'/{self.slug}/'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...