models.py 860 B

1234567891011121314151617181920212223242526272829303132333435
  1. import secrets
  2. from functools import partial
  3. from django.db import models
  4. from django.utils import timezone
  5. from django.contrib.auth import get_user_model
  6. User = get_user_model()
  7. class TempToken(models.Model):
  8. user = models.ForeignKey(User, on_delete=models.CASCADE)
  9. key = models.CharField(
  10. max_length=171,
  11. default=partial(secrets.token_urlsafe, 128),
  12. blank=True,
  13. db_index=True,
  14. editable=False
  15. )
  16. created = models.DateTimeField(auto_now=True, blank=True)
  17. expires_on = models.DateTimeField(null=True, default=None, blank=True)
  18. @property
  19. def expired(self):
  20. return self.expires_on <= timezone.now()
  21. def expire(self):
  22. self.expires_on = timezone.now()
  23. self.save(update_fields=('expires_on',))
  24. return self
  25. def __str__(self):
  26. return self.key