'How to Override get_absolute_url in Django for different Fields?

I want to make the method get_absolute_url to be dynamic with different class based views.

So if in a template where it displays a list of all the articles in the database I call the function for the attribute as {{ instance.get_absolute_url }}, that link will take me to blog/article/title.

But then I want to have a page that displays all the authors in the database and when I click in an author, the next page would display all the articles of that author, so the url would be blog/author/authorname.

The problem is that I overrode the method in the Article class as follows:

reverse(blog:article-detail, kwargs={'title': self.title})

What do I have to do to implement a conditional that checks whether I am looking for the author or the title.

I've tried overriding the method inside the AuthorArticleListView class that I created to render the template where the author's articles will be displayed but when calling the get_absolute_url method in the template, the link would just not work and stays in the same page, does not even give me an error but when called for the articles to go into the DetailView of each article from the ListView, it works just fine.

These are the paths:

path('author/<str:author>/',AuthorArticleListView.as_view(),name='author-article-list') path('article/<str:title>/',ArticleDetailView.as_view(),name='article-detail')

The html lines that are basically the same for both views:

<li class="list-group-item">
   <a href="{{ instance.get_absolute_url }}">{{ instance.title }}</a>
</li>


Solution 1:[1]

A get_absolute_url should be just that, absolute. It shouldn't return two different forms. It should take you to the definitive detail view of that model.

You could use the get_absolute_url of the Author model if the definitive view of that model was a list of their articles. Or you could simply use the constructor {% url 'author-article-list' author %} in your template.

I'm not sure why your links in the AuthorArticleListView don't work, especially if {{ instance.title }} is showing properly. If that isn't the case, try just showing {{ instance }} for the link text and see what is in there that you can reference.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SamSparx