How to build a get_absolute_url with year, month, day and slug on Djano Rest Framework

I'm building a blog aplication with DRF, and I want it to be able to get my get_absolute_url method for wach post, like: And not the default:

Here's my model:

class Post(models.Model):
    ('draft', 'Draft'), ('published', 'Published')
title = models.CharField(max_length=250)
slug = models.SlugField(unique_for_date='publish', max_length=250)
body = models.TextField()

author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts')

publish = models.DateTimeField(
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name="posts" ,blank=True, null=True )

objects = models.Manager()
published = PublishedManager()

tags = TaggableManager()

feature_image = models.ImageField(upload_to="uploads/", null=True, blank=True)

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

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', args=[self.publish.year,
                                             self.slug], )

And my serializer:

class BlogSerializer(serializers.HyperlinkedModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
url = serializers.CharField(source='get_absolute_url', read_only=True)

class Meta:
    model = Post
    fields = ['url', 'id', 'title', 'slug', 'body', 'author', 'publish', 'created_at', 'updated_at',
    'status', 'category', 'feature_image']

Somebody help how to do that, please. thanks!

From what you've posted and what I've seen you don't seem to be doing anything wrong.
Could you describe what that spits out?- is it crashing?- is the url wrong?- does it need the website prefix?

I've also seen this, /, which might be a route you could take. (I've done this with custom admin pages)

class BlogSerializer(serializers.HyperlinkedModelSerializer):
  url = serializers.SerializerMethodField()

  def get_url(self, obj):
    return obj.get_absolute_url()

  class Meta:
    model = Post
    fields = ['url', 'id', 'title', 'slug', 'body', 'author', 'publish', 'created_at', 'updated_at',
    'status', 'category', 'feature_image']
Back to Top