Django: How to check if a user has signed up within the last 7 days?

Viewed 116

I'm trying to allow users to have access to my app for 7 days after they register with this function:

from datetime import datetime, timedelta
from django.utils import timezone
from django.utils.timezone import localdate

    class CustomUser(AbstractUser):
    
        def free_trial(self):
            if (self.date_joined - timezone.now()) < timedelta(days=7):
                return True

But testing with accounts made more than 7 days ago i can still see the h1 tag below

  {% if user.free_trial %}
    <h1> Your trial has started </h1>
    
    {% endif %}
1 Answers

You need to subtract the current datetime() from the self.date_joined, not the opposite way, otherwise it will be minus seven days, which is always less than seven days, so:

class CustomUser(AbstractUser):
    
    def free_trial(self):
        return (timezone.now() - self.date_joined) < timedelta(days=7)
Related