Reputation: 5402
I'm getting an 404
error when trying to post. But the error is event objects don't have get_absolute_url() methods
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
date = models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
avatar = models.ImageField(upload_to='avatars/events/', null=True, blank=True)
tags = models.ManyToManyField(Tag, null=True, blank=True)
class Meta:
ordering = ['-date']
def __unicode__(self):
return self.title
# I made this, but this doesn't work
def get_absolute_url(self):
return "/event/" + self.id
# it returns :
Exception Type: TypeError
Exception Value: cannot concatenate 'str' and 'int' objects
How do I properly make this work? Thanks for you help in advance.
Upvotes: 0
Views: 682
Reputation: 906
self.id is a number and you're trying to convert it to number in url... you can still do "+" operation if you convert it's type to desired string... so you must do:
def get_absolute_url(self):
return "/event/" + str(self.id)
and it will work. This way you can do Unicode conversions and so on... By specifying exact type you want an output to be. However other constructions seem to be quicker. But I prefer this one because of visual clarity in what's going on in this piece of code...
Upvotes: 0
Reputation: 6052
The return
value from get_absolute_url
is trying to combine a string and number.
def get_absolute_url(self):
return "/event/{0}".format(self.id)
Upvotes: 0
Reputation: 1754
You need to use a format string.
def get_absolute_url(self):
return "/event/%d" % self.id
Upvotes: 3