python - Best way to delete a django model instance after a certain date -
i writing little app user creates event , specifies date event occur. after event date has past, want delete event instance. current attempt throwing function checks if event should expire in event page view. not sure whether expiration_check function checking in correct way, nor sure whether having function in view event work.
here view , expire function:
def event_page(request, name): event = event.objects.get(name=name) check_expiration(event) if request.method == "post": form = guestform(request.post) if form.is_valid(): guest = form.save(commit=false) guest.event = event guest.save() return redirect(event) else: form = guestform() return render(request, "event_page.html", {"form": form, "event": event, }) def check_expiration(event): = datetime.datetime.now() if event.date < now: #if event date has past event.delete()
i collect date user , store in datetime filed: date = models.datefield()
let me know if further details needed. insight appreciated, thanks!
if you're hosting application on unix platform (gnu/linux, osx, etc.), it's best make use of cron
, generic system utility running things periodically.
this requires implementing expiry code custom management command:
if don't have custom management commands already, create following directory structure:
yourapp/ management/ __init__.py (blank) commands/ __init__.py (blank) expire_events.py
in
expire_events.py
, create new class along lines of following:from django.core.management.base import noargscommand class command(noargscommand): = 'expires event objects out-of-date' def handle_noargs(self): print event.objects.filter(date__lt=datetime.datetime.now()).delete()
now should able run
./manage.py expire_events
, have events expiry dates in past deleted.
to run @ regular intervals using cron
(these instructions gnu/linux may work on other unix variants), run sudo crontab -e
, add following line:
*/5 * * * * /path/to/your/django/app/manage.py expire_events
(this run task every 5 minutes; see the crontab documentation advice on specifying job run times)
Comments
Post a Comment