创建get_absolute_url()

时间:2012-07-30 20:49:49

标签: python django django-models

我在尝试发帖时遇到404错误。但错误是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

我如何正确地完成这项工作?谢谢你提前帮忙。

3 个答案:

答案 0 :(得分:3)

您需要使用格式字符串。

def get_absolute_url(self):
    return "/event/%d" % self.id

答案 1 :(得分:0)

来自return的{​​{1}}值正在尝试合并字符串和数字。

get_absolute_url

答案 2 :(得分:0)

self.id是一个数字,你试图将它转换为url中的数字... 如果将其类型转换为所需的字符串,您仍然可以执行“+”操作... 所以你必须这样做:

def get_absolute_url(self):
    return "/event/" + str(self.id)

它会起作用。这样你可以进行Unicode转换等等......通过指定你想要输出的确切类型。 然而,其他结构似乎更快。但我更喜欢这个,因为这段代码中的内容视觉清晰......

相关问题