简体   繁体   English

如何在 django 中添加倒数计时器作为用户字段?

[英]How to add a countdown timer as a user field in django?

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.因此,如果您有一个 10 小时的帐户,则有一个字段可以倒计时这 10 小时。 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:现在我有一个带有 time_left 字段的自定义 model :

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:然后我有一个上下文处理器来显示 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.编辑:考虑一下,更新页面本身剩余时间的唯一方法可能是 JQuery 和 AJAX。 Am I correct in this assumption?我在这个假设中正确吗? Still need to update the number in the backend though.不过,仍然需要更新后端的号码。

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.如果您只想显示 10 小时倒计时显示,我认为每秒通过 AJAX 从后端请求时间不是有效的 - 最简单的方法可能是获取该时间左变量一次(使用您的time_left function 从服务器端,然后使用javascript 在页面上倒计时。

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您可以看到这个页面https://www.w3schools.com/howto/howto_js_countdown.asp了解如何在 JS 中制作倒数计时器显示,然后只需替换该行

var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();

with your ajax code that gets remaining time from the server.使用从服务器获取剩余时间的 ajax 代码。

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.但是,如果您想限制用户在网站上的停留时间,唯一的方法是 javascript(是的,通过 GET/POST 请求每秒使用 AJAX 更新它),但这可以绕过用户在创建帐户后使用网站时只需禁用 js。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM