Reputation: 523
I'm trying to set a get_absolute_url()
function for the Entry
class, but failing. I have successfully created such a function for the Category
class, with only one arg, but am stuck on using multiple args as in the Entry
class.
Currently, clicking a
<a href="/blog/{{ entry.get_absolute_url }}/">{{ entry.title }}</a>`
link, as appears on my index page, only returns the url below:
http://127.0.0.1:8000/blog//
I originally used returns without reverse like this:
def get_absolute_url(self):
return "/%s/%s/%s/" % (self.pub_date.year, self.pub_date.month, self.slug)
but, whilst it worked from index.html with the earlier mentioned href
, from other pages (i.e. category.html
) this returned a URL with this appended upon the current URL, including for the Category
class. Switching to reverse fixed this issue for Category
, but I couldn't get it to work for Entry
, because of the multiple args.
Please request any additional data as is desirable.
Edit: Well, I've managed to make it work with(the original code):
def get_absolute_url(self):
return "%s/%s/%s/%s" % (self.pub_date.year, self.pub_date.month, self.pub_date.day, self.slug)
by changing the href
at category.html to:
<a href="http://127.0.0.1:8000/blog/{{ entry.get_absolute_url }}">{{ entry.title }}</a>
i.e. I added the root http://127.0.0.1:8000
, but I still can't get it to work with reverse()
... I've tried args
, kwargs
, some other things... I'm not actually sure still what reverse()
does differently though to a regular return
. It did something differently, as before when I was using the "blog/{{ category.get_absolute_url }}"
without the root, switching from return
to return reverse()
made it work; although I've now managed to get it to work with just return
, by adding the root to the href
as I did with Entry
.
Upvotes: 2
Views: 1642
Reputation: 15221
You can use kwargs
with reverse. Something like:
Assuming your url pattern for blog detail is like:
url(r'^blog/(?P<year>)/(?P<month>)/(?P<slug>[-\w]+)/$', 'details', name='blog_details')
You can write get_absolute_url as:
def get_absolute_url(self):
return reverse('blog_details', kwargs={'year': self.pub_date.year,
'month': self.pub_date.month,
'slug': self.slug})
And use it in template as you are using.
Upvotes: 2