I want to set a time limit for object deletion in Django.
For example, the user can delete the object they submitted within 3 days; once the 3-days window is past, they can no longer delete the object. 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.. delete()
and timedelta to calculate the age of the instance. raise
the correspondent error & catch
when necessary 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.
One solution would be to override the delete()
method of the models and add a check there, maybe something like this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.