0

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.

CyberDemic
  • 180
  • 2
  • 6
  • Possible duplicate of [How can I get the full/absolute URL (with domain) in Django?](https://stackoverflow.com/questions/2345708/how-can-i-get-the-full-absolute-url-with-domain-in-django) – w411 3 Oct 24 '19 at 01:24
  • Thank you for the link, I will check it out more today. I think I just need to read some more documentation =) – CyberDemic Oct 24 '19 at 23:10

1 Answers1

0

So I ended up getting rid of the onclick="document.location" stuff and just wrapped the <div> in a a href="{{ category.get_absolute_url }}"> and the links work just fine.

CyberDemic
  • 180
  • 2
  • 6