[英]How to set a time limit for model object delete in django?
I want to set a time limit for object deletion in Django. 我想为Django中的对象删除设置时间限制。
For example, the user can delete the object they submitted within 3 days; 例如,用户可以在3天内删除他们提交的对象; once the 3-days window is past, they can no longer delete the object. 一旦过去了3天,他们将无法再删除该对象。 After that, only the superuser can delete it. 此后,只有超级用户才能删除它。
How can I achieve that? 我该如何实现? I tried lots of methods but none can do this...could someone help with the solutions? 我尝试了很多方法,但是没有一种方法可以解决……有人可以提供解决方案吗?
DateTimeField
with auto_now_add to set the field to now when the object is first created.. 使用DateTimeField
和auto_now_add将字段设置为现在第一次创建对象时的时间。 delete()
and timedelta to calculate the age of the instance. 在删除之前比较一下自创建以来已经过去了多少天,请在执行delete()
和timedelta来计算实例的使用期限之前,使用django预删除信号触发检查。 raise
the correspondent error & catch
when necessary raise
相应的错误并在必要时catch
pro-tip: if you write a Model method obj.can_delete(self, user)
you can write logic for 2 and 3 here instead having it across different parts of the app, then you can ask can_delete(user)
first in order to present warnings or deactivate buttons, the user
instance works for the conditional statement to allow only superusers to delete ignoring the age contitioning. 专家提示:如果您编写模型方法obj.can_delete(self, user)
,则可以在此处编写2和3的逻辑,而不是在应用程序的不同部分使用它,那么您可以先询问can_delete(user)
以便进行演示警告或停用按钮, user
实例适用于条件语句,以仅允许超级用户删除忽略年龄竞争的内容。
One solution would be to override the delete()
method of the models and add a check there, maybe something like this: 一种解决方案是重写模型的delete()
方法并在其中添加检查,也许是这样的:
from datetime import timedelta
from django.utils import timezone as tz
def delete(self, *args, **kwargs):
user = kwargs['user'] # this may raise KeyError
start_date = ... # this probably would be a model field
if user.is_superuser or (tz.now() < start_date + timedelta(days=3)):
super().delete(*args, **kwargs)
else:
raise some error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.