[Answered ]-How can I create in Django a custom absolute url for a predefined class

1👍

✅

You can make a proxy model [Django-doc], this is not a new (real) model. Behind the curtains, it uses the User model, but it converts it to Author objects, and we can add logic to that Author object:

from django.contrib.auth.models import User


class Author(User):
    class Meta:
        proxy = True

    def get_absolute_url(self):
        return reverse('blogger-detail', args=(self.pk,))

and then use that proxy model in the ForeignKey instead:

class Blog(models.Model):
    name = models.CharField(max_length=200, help_text='Enter name')
    author = models.ForeignKey(
        Author, on_delete=models.CASCADE, null=True, blank=True
    )

then in the template, you use:

<a href="{{ blog.author.get_absolute_url }}">link</a>

Leave a comment