Django [SOLVED]: How can I check whether time from model object created time is over 10mins?

Django [SOLVED]: How can I check whether time from model object created time is over 10mins?

Home Forums Frameworks Django Tutorials Django [SOLVED]: How can I check whether time from model object created time is over 10mins?

Tagged: ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #246536

    Cloudy Point
    Keymaster

    QuestionQuestion

    models.py

    @python_2_unicode_compatible
    class UserAuthToken(models.Model):
    
        email = models.ForeignKey(UserSubEmail)
        token = models.CharField(max_length=34, unique=True)
        created = models.DateTimeField(auto_now_add=True)
    
        def __str__(self):
            return "AuthToken for %s" % self.email
    

    I want to check elapsed time between token’s created time and now So if token created before more than 10 minutes, I can recognize this token is invalid.

    views.py

    def create_email_confirm_key(request, uid, token):
        try:
            user_authtoken = UserAuthToken.objects.get(uid=uid)
        except (TypeError, ValueError, OverflowError, User.DoesNotExist):
            user_authtoken = None
    
        if not 'user_authtoken is created before more than 10minutes' :
            This token is valid and do something
    

    How can I check whether time between the token created and now is more than 10mins?

    #246537

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    You can always calculate the delta from the current time using django.utils.timezone:

    from django.utils.timezone import now, timedelta
    
    if now() - user_authtoken.created <= timedelta(seconds=10*60):
        # token valid
    

    But I recommend you take a look at django’s Cryptographic signing. It lets you verify timestamped signatures and handles all the delta calculations for you.

    Source: https://stackoverflow.com/questions/47971191/how-can-i-check-whether-time-from-model-object-created-time-is-over-10mins
    Author: schwobaseggl
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.