Derrick Sherrill
Derrick Sherrill

Reputation: 96

Appending URL with query object

I'm querying a database for objects and passing it to my html file through my view. The way I have my urls.py set up is such that /index/object_primary_key - Therefore, each object in my database has its own URL.

This is the code I typed thinking it would work, but I now know the URL function doesn't work that way:

<a href="{% url 'index'%} {{object.pk}}">{{object.title}}</a>

Is there a way to use a query and append it to a url?

Upvotes: 0

Views: 48

Answers (2)

John Bobst
John Bobst

Reputation: 157

Try "{% url 'index' pk=object.pk %}"

Upvotes: 0

Lemayzeur
Lemayzeur

Reputation: 8525

After setting up your url pattern correctly, the simpler way is:

{% url 'index' object.pk %}

But the most effective is get_absolute_url() method in your model class: (In most cases, used because of slug in url)

This tells Django how to calculate the canonical URL for an object. It returns a string that can be used to refer to the object over HTTP.

I suppose that you have your urls pattern set as the following

url(r'index/(?P<pk>\d+)',index,name='index')

The method will be:

from django.urls import reverse

class ModelClass(models.Model):
    ''' fields '''
    def get_absolute_url(self):
        return reverse('index', args=[str(self.pk)])
        # or with kwargs={'pk':str(self.pk)}

In your template, you may call it that way

<a href="{{object.get_absolute_url}}">See me</a>

Upvotes: 2

Related Questions