Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 一周后禁用按钮_Python_Django - Fatal编程技术网

Python 一周后禁用按钮

Python 一周后禁用按钮,python,django,Python,Django,我做了一个页面,你可以在那里发表评论。你也可以用删除按钮删除你的评论。我想要的是,在你发表评论后,你有一周的时间删除它。所以一周后我想隐藏删除按钮 尝试执行此操作时,我遇到以下错误: “age不是一个整数,而是一个timedelta实例。您需要将比较更改为: if age.total_seconds() < 604800: 或 这不是django的问题,而是python的日期时间问题: >>> from datetime import datetime >>

我做了一个页面,你可以在那里发表评论。你也可以用删除按钮删除你的评论。我想要的是,在你发表评论后,你有一周的时间删除它。所以一周后我想隐藏删除按钮

尝试执行此操作时,我遇到以下错误: “age不是一个整数,而是一个timedelta实例。您需要将比较更改为:

if age.total_seconds() < 604800:


这不是django的问题,而是python的日期时间问题:

>>> from datetime import datetime
>>> then = datetime.now()
>>> now = datetime.now()
两个日期时间之间的差异是一个时间差:

>>> now - then
datetime.timedelta(0, 7, 452120)
这是你无法与数字相比的:

>>> (now - then) < 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.timedelta to int
但您可以转换为秒和分钟等,并比较:

>>> (now - then).seconds < 5
False
>>> (now - then).seconds 
7

django可能存在的问题是,尽管您可能没有删除旧注释的按钮,但这不会阻止客户端发送删除请求-因此,请确保您在服务器上的视图处理程序中捕获尝试删除旧注释的行为。

您无法比较int和datetime。尝试以下方法:

from datetime import datetime
now = datetime.now()
from datetime import timedelta
time_to_delete = timedelta(weeks=1)
comment1 = datetime(2018, 1, 15)
comment2 = datetime(2018, 1, 2)
now - time_to_delete <= comment1  # True
now - time_to_delete <= comment2  # False

作为评论模型上的一种方法,这会更好,你可以在模板中调用它,这样你就不需要在视图中迭代了。非常感谢你的帮助,我一定会遵循你关于视图处理程序的提示!
>>> now - then
datetime.timedelta(0, 7, 452120)
>>> (now - then) < 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.timedelta to int
>>> (now - then).seconds < 5
False
>>> (now - then).seconds 
7
from datetime import datetime
now = datetime.now()
from datetime import timedelta
time_to_delete = timedelta(weeks=1)
comment1 = datetime(2018, 1, 15)
comment2 = datetime(2018, 1, 2)
now - time_to_delete <= comment1  # True
now - time_to_delete <= comment2  # False