I am writing a little app where the user creates an event and specifies the date that event will occur. After the event date has past, I want to delete that event instance. My current attempt is throwing a function that checks if the event should expire in the event page view. I am not sure whether the expiration_check function is checking in a correct way, nor am I sure whether just having a function in the view will event work.
Here is my view and 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):
now = datetime.datetime.now()
if event.date < now: #if the event date has past
event.delete()
I collect the date from the user and store it in a DateTime filed: date = models.DateField()
Let me know if any further details are needed. Any insight is appreciated, thanks!
To delete multiple records you use the delete() method and append it to a query.
To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.
If you're hosting your application on a UNIX platform (GNU/Linux, OSX, etc.), it's probably best to make use of cron
, the generic system utility for running things periodically.
This requires implementing your expiry code as a custom management command:
If you don't have any custom management commands already, create the following directory structure:
yourapp/
management/
__init__.py (blank)
commands/
__init__.py (blank)
expire_events.py
In expire_events.py
, create a new class along the lines of the following:
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
help = 'Expires event objects which are out-of-date'
def handle_noargs(self):
print Event.objects.filter(date__lt=datetime.datetime.now()).delete()
Now you should be able to run ./manage.py expire_events
and have any events with expiry dates in the past deleted.
To run this at regular intervals using cron
(these instructions are for GNU/Linux but may well work on other UNIX variants), run sudo crontab -e
and add the following line:
*/5 * * * * /path/to/your/django/app/manage.py expire_events
(this would run the task every 5 minutes; see the crontab documentation for advice on specifying job run times)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With