场景:
目前,我的模板有一个文字“最后一次看到”和一个计时器,上面提到了单击按钮后产生的时间。如果有新用户访问该站点,则不会显示任何时间。如果用户单击按钮,则将在模型中生成和创建时间。并且,每当用户刷新页面时,旧时间/当前时间应显示在文本附近。现在,每次我重新加载页面时,尽管已保存在模型中,但没有任何时间显示。每次重新加载后如何在模板中显示当前时间?
到目前为止,这是我尝试过的:
models.py:
from django.contrib.auth.models import User
class Path(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
current_time = models.DateTimeField(blank=True, null=True) #can be Null or blank if users enters the site for the first time.
views.py:
from django.utils import timezone
import pytz
from django.http import JsonResponse, HttpResponse
def Func():
'''
If the current_time does not exist, then we create it in the Path model.
#If time already exists, then we grab the id and replace current time with a new one using the update() method.
'''
time = timezone.now() #Format: 2019-11-16 14:53:35.774824+00:00
user_id = request.user.id #User id = 1
if (Path.objects.filter(current_time = time) in (None, '')):
time = Path.objects.create(current_time = time)
else:
time = Path.objects.filter(user_id=user_id).update(current_time = time)
obj = Path.objects.values_list('current_time', flat=True)
return HttpResponse(obj)
home.html:
... HTML stuff here
#If time exists in model, then display it in Template (even after refreshing/reloading)
{% if obj.current_time %}
<div class="placeRight">
<p> Last indexed:
<b> {{obj.current_time}}</b>
</p>
</div>
#If time doesn't exist, then display None (this will only occur if a user enters the site for the first time).
{% else %}
<div class="placeRight">
<p> Last indexed:
<b> None </b>
</p>
</div> -->
{% endif %}
如前所述,每次重新加载页面后,时间显示为“无”,我必须继续单击该按钮以显示时间。有没有办法查看每次重新加载后的时间(如果存在)?
欢迎使用StackOverflow。
您需要将上下文发送回模板
这是你的看法应该如何改变
from django.template import loader # I added this line
def Func():
'''
If the current_time does not exist, then we create it in the Path model.
#If time already exists, then we grab the id and replace current time with a new one using the update() method.
'''
time = timezone.now() #Format: 2019-11-16 14:53:35.774824+00:00
template = loader.get_template('home.html') # I added this line
user_id = request.user.id #User id = 1
if (Path.objects.filter(current_time = time) in (None, '')):
time = Path.objects.create(current_time = time)
else:
time = Path.objects.filter(user_id=user_id).update(current_time = time)
obj = Path.objects.values_list('current_time', flat=True)
context = {
'obj':obj
}
return HttpResponse(template.render(context, request))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句