0

我正在尝试在管理界面中调整显示。我需要其中一个字段来显示为我正在创建的照片共享网站提交的名称和日期,但我不断收到以下错误:

global name 'datetimeConvertToHumanReadable' is not defined

这是完整的追溯:http ://dpaste.com/822073/

我的代码

模型:

class Design(models.Model):
    designer_id = models.ForeignKey(User)
    date_submitted = models.DateTimeField()
    title = models.CharField(max_length=70)
    description = models.TextField()
    photo = models.FileField(upload_to='design_photos')

    def image_thumb(self):
        return '<img src="/media/%s" width="100" height="100" />' % (self.photo)
    image_thumb.allow_tags = True

    def datetimeConvertToHumanReadable(dt):

        # convert passed datetime to timestamp
        dt_stamp = dt.strftime("%s")

        # convert current datetime to timestamp
        now = datetime.datetime.now()
        now_stamp = now.strftime("%s")

        # find difference between the two
        delta = int(now_stamp) - int(dt_stamp)

        # convert to (seconds ago, minutes ago, hours ago, etc...)
        if (delta < 60):
            return str(delta) + " seconds ago"
        elif (delta < 3600):
            return str(delta/60) + " minutes ago"
        elif (delta < 86400):
            return str(delta/3600) + " hours ago"
        elif (delta < 31536000):
            return str(delta/86400) + " days ago"
        else:
            return str(delta/31536000) + " years ago"

    def name_and_submitted(self):
        date_submitted = datetimeConvertToHumanReadable(date_submitted) 
        return '<div>%s<br />submitted %s ago</div>' % (self.designer_id, self.date_submitted)

    def __unicode__(self):
        return self.title

管理员.py:

class DesignAdmin(admin.ModelAdmin):

    list_display = ('image_thumb', 'title', 'description', 'name_and_submitted')

image_thumb 方法可以很好地在字段中显示缩略图,但 name_and_submitted 方法会引发错误。有任何想法吗?

4

1 回答 1

0

只是通过self论据。那应该可以解决问题

def datetimeConvertToHumanReadable(self):
    dt = self.date_submitted
    # rest of your code goes here

问题是,当您不传递self参数时,该函数不会附加到类并且不能通过模型​​对象调用。list_admin_display 实际访问模型实例并调用该函数。在您的情况下,它类似于design_object.datetimeConvertToHumanReadabledesign_object 是管理页面中显示的每个模型实例。该参数dt不作为参数传递,因此您需要在函数中提取它。

希望这可以帮助

于 2012-11-01T11:21:41.193 回答