简体   繁体   中英

How to set a time limit for model object delete in django?

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?

  1. store the "object creation" date in the instance to be processed. use DateTimeField with auto_now_add to set the field to now when the object is first created..
  2. before deleting compare how many days have passed since the creation, use django signals pre-delete to trigger a check before executing the delete() and timedelta to calculate the age of the instance.
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM