Reputation: 1
I want for every user on an application that they have a field with a certain time, which gets used up when using the website. So if you have an account with 10 hours, there is a field that counts down those 10 hours. Is there any existing way how to do this and have it continuously update?
Right now I have a custom model with a time_left field:
class User(AbstractBaseUser, PermissionsMixin):
"""
Custom user class which overrides the default user class.
"""
email = models.EmailField(max_length=254, unique=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
time_left = models.TimeField(default=datetime.time(0, 0))
And then I have a context processor to display the time_left:
def time_left(request):
time = datetime.time(0, 0)
if request.user.is_authenticated:
user = User.objects.get(email=request.user.email)
time = user.time_left
print(time)
return {'time_left': time}
Edit: Thinking about it, the only way to update the time left on the page itself is probably like JQuery and AJAX. Am I correct in this assumption? Still need to update the number in the backend though.
Upvotes: 0
Views: 1720
Reputation: 51
If you just want a 10 hour countdown display, I don't think requesting the time from backend via AJAX every second is efficient - the easiest way would probably be getting that time left variable once (with your time_left
function from server side, then using javascript to count it down on the page.
You can see this page https://www.w3schools.com/howto/howto_js_countdown.asp for how to make a countdown timer display in JS, then just replace the line
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
with your ajax code that gets remaining time from the server.
However, if you want to limit the amount of time the user has on the site, the only way to do this is javascript (yes, updating it down w/ AJAX every second via a GET/POST request), but that can be bypassed by the user simply disabling js when using the site after they create an account.
Upvotes: 1