1👍
Just make a filter that prevents retrieving expired VerificationToken
s:
from datetime import timedelta
from django.db.models.functions import Now
VerificationToken.objects.filter(
date_created__gte=Now()-timedelta(minutes=10)
)
You can also make a manager such that VerificationToken.objects
is a manager that only contains non-expired tokens:
from datetime import timedelta
from django.conf import settings
from django.db.models.functions import Now
class VerificationTokenManager(models.Manager):
def get_queryset(self):
return super().get_querset().filter(
date_created__gte=Now()-timedelta(minutes=10)
)
class VerificationToken(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
code = models.CharField(max_length=4)
date_created = models.DateTimeField(auto_now_add=True, db_index=True)
objects = VerificationTokenManager()
you can then make a management command [Django-doc] that you for example run through cron, or some other scheduling task that removes expired VerificationToken
s with:
# app_name/management/commands/remove_expired_tokens.py
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.db.models.functions import Now
from app_name.models import VerificationToken
class Command(BaseCommand):
help = 'Remove expired verification tokens'
def handle(self, *args, **options):
VerificationToken._base_manager.filter(
date_created__lt=Now()-timedelta(minutes=10)
).delete()
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
0👍
I believe that Django does’t provide that kind of functionality. You can use Celery to create a celery task that will delete tokens that expires after certain amount of time. Also you can create task that will periodically find expired tokens and will delete them.
0👍
Unfortunately it’s not possible. What you can do is to create a cronjob using celery-beat or what you like and set a cronjob task to clean up expired DB records (once per minute/hour/day)
- [Answered ]-How can I convert django serializer result to dict?
- [Answered ]-Django select_related works in template rendering?
- [Answered ]-Using django-syncr with twitter
- [Answered ]-Django-embed-video – how to use Vimeo options