Django站点地图“发布”对象没有属性“ get_absolute_url”吗?

时间:2019-01-25 02:08:49

标签: python django

我正在创建一个简单的django 1.9应用程序,其中包括一个博客,并且我希望该站点具有包含网站页面和博客文章条目的站点地图。到目前为止,我已经能够构建一个站点地图,该站点地图将静态页面生成为站点地图但是博客文章站点地图给我一个错误'Post' object has no attribute 'get_absolute_url,这是我的代码。有人请告诉我我要去哪里了。

sitemaps.py

from django.contrib import sitemaps

from django.contrib.sitemaps import Sitemap

from django.core.urlresolvers import reverse

from administration.models import Post


class StaticSitemap(sitemaps.Sitemap):

      changefreq = "daily"

      priority = 1.0



     def items(self):

          return ['administration:index', 'administration:about']



     def location(self, item):
          return reverse(item)



class PostSitemap(Sitemap):

      changefreq = "daily"

      priority = 0.5


      def items(self):
          return Post.objects.all()`

models.py

class Post(models.Model):
    STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),)
    featured_image = models.ImageField(upload_to="Photos/posts/images", blank=True, null=True)
    post_short_description = models.TextField(default="No description available")
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    category = models.ForeignKey(Category)
    tag = models.ManyToManyField(Tag)
    author = models.ForeignKey(User,related_name='blog_posts',on_delete=models.CASCADE)
    body = RichTextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES,default='draft')

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.title

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from administration.sitemaps import PostSitemap, StaticSitemap

sitemaps = {
   'post':PostSitemap,'static':StaticSitemap
}

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('administration.urls')),
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, 
    name='django.contrib.sitemaps.views.sitemap'),
    url(r'^robots\.txt', include('robots.urls')),
    url(r'^', include('cms.urls'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

1 个答案:

答案 0 :(得分:1)

当您使用Sitemap类并且自己没有实现location()方法时,默认值为在每个对象上调用get_absolute_url()

https://docs.djangoproject.com/en/2.1/ref/contrib/sitemaps/#a-simple-example上的文档说:

  

在此示例中没有定位方法,但是您可以提供该方法来指定对象的URL。默认情况下,location()在每个对象上调用get_absolute_url()并返回结果。

因此,您应该在location()上实现PostSitemap,或者在get_absolute_url()模型上实现Post