'Post' object has no attribute 'get_absolute_url' Django

Viewed 220

I am trying to create a sitemap in Django but I am getting an error

'Post' object has no attribute 'get_absolute_url'

Here is my anotherfile/sitemap.py

from django.contrib.sitemaps import Sitemap
from somefile.models import Post

class site_map(Sitemap):
    changefreq = "daily"
    priority = 0.8

    def items(self):
        return Post.objects.all()
    def lastmod(self, obj):
        return obj.time_stamp

and here is my somefile/models.py

class Post(models.Model):
    number=models.AutoField(primary_key=True)
    slug=models.CharField(max_length=130)
    time_stamp=models.DateTimeField(blank=True)

def __str__(self):
        return self.number
2 Answers

In order to determine the paths in the sitemap, you need to implement a get_absolute_url for the model(s) for which you make a sitemap, so:

from django.urls import reverse

class Post(models.Model):
    number=models.AutoField(primary_key=True)
    slug=models.CharField(max_length=130)
    time_stamp=models.DateTimeField(blank=True)

    def get_absolute_url(self):
        return reverse('name-of-some-view', kwargs={'para': 'meters'})

    def __str__(self):
        return self.number

With reverse(…) [Django-doc] you can calculate the URL based on the name of the view, and parameters that the corresponding path needs.

I've never used it, but it simply sounds like your Post model doesn't have a get_absolute_url method.

http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/#django.contrib.sitemaps.Sitemap.location

If location isn't provided, the framework will call the get_absolute_url() method on each object as returned by items().

Model.get_absolute_url()

Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.

For example:

def get_absolute_url(self):
    return "/post/%i/" % self.id
Related