I am trying to use the get_absolute_url function in one of my templates like so:
template.html
<div class="card-columns">
{% for category in main_categories %}
<div onclick="document.location = {{ category.get_absolute_url }};" class="card">
I'm fairly new to programming in general so I'm not sure if that is the correct way to do it, but I have been able to get it to return a couple views individually by using if statements like this:
models.py
def get_absolute_url(self):
if self.pk == 1:
return reverse('forum:index')
if self.pk == 2:
return reverse('tutorials:cybertips')
return reverse('tutorials:subjects', args=[str(self.pk)])
I don't get any errors, and when clicking on the cards with pk=1 & pk=2 it returns the correct url pattern. The other cards loads fine but don't link to anything. When inspecting the html it looks like it returns a url so I'm wondering if i'm not understanding the onclick function? Here are my urls(in this app):
urls.py
app_name = 'tutorials'
url_patterns = [
path('category/<int:pk>/', views.SubjectView.as_view(), name='subjects'),
path('cybertips/', views.cybertips, name='cybertips'),
]
views.py
class MainCategoriesView(ListView):
model = MainCategory
context_object_name = 'main_categories'
class SubjectView(ListView):
model = Subject
context_object_name = 'subjects'
Any help is appreciated. Or if there is a more efficient and safe way to do it. Thank you.