Django检查已用时间

时间:2013-09-06 17:54:23

标签: python django

我正在Django中编写一个URL缩短应用程序。我想检查URL是否过期的地方(URL仅在3小时内有效)。下面是我的models.py但它不起作用 我收到错误can't subtract datetime object

import uuid
import base64
import datetime
from django.db import models
from django.contrib import admin
#------------------------------------------------------------------------------ 

def _generateShortUrl():
    """
        This function will generate base64 encoded id
    """
    return base64.urlsafe_b64encode(uuid.uuid1().bytes)[:6]


class link(models.Model):
    """
        This is a link class 
    """
    link = models.URLField()                                    # To store user entered URL
    hits = models.IntegerField(default=0)                       # How many hits for particular URL
    last_used = models.DateTimeField(auto_now=True)             # When URL is last used 
    short_url = models.CharField(max_length=6,unique=True)      # base64 URL encoded id  

    def linkValidate(self):
        timediff = datetime.datetime.now() - self.last_used                       
        return timediff.min

    def save(self, *args, **kwargs):
        """
            Custom Save method for link model 
        """
        self.short_url = _generateShortUrl()        
        super(link, self).save(*args, **kwargs)   


class user_info(models.Model):
    """
        This is a user_info class 
    """
    user_agent = models.TextField()                 # Stores user_agent name used by user
    user_ip = models.ManyToManyField(link)          # Stores user's IP

    def userIP(self):
        """Method to return tags related to store"""
        return ','.join([t.link for t in self.link.all()])

#------------------------------------------------------------------------------ 

class linkAdmin(admin.ModelAdmin):
    """
        link admin class
    """
    list_display = ('link','hits','short_url','last_used',
                    'linkValidate')
    ordering = ('hits',)

class userInfoAdmin(admin.ModelAdmin):
    """
        user_info admin class
    """
    list_display = ('user_agent','userIP')

#------------------------------------------------------------------------------ 
admin.site.register(link,linkAdmin)
admin.site.register(user_info,userInfoAdmin)

有人可以帮帮我吗。

1 个答案:

答案 0 :(得分:3)

由于您启用了时区支持,self.last_used是时区感知的日期时间对象,datetime.datetime.now()不是。

请改为尝试:

timediff = datetime.datetime.utcnow() - self.last_used.replace(tzinfo=None)

另一个选择是使用now()

来识别您的make_aware()时区
from django.utils import timezone
now = timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone())
timediff = now() - self.last_used

另见: