【发布时间】:2021-12-25 19:51:01
【问题描述】:
我想在返回渲染后刷新页面。我可以在同一个页面上使用return redirect,但是如果我可以在同一个视图函数中同时使用返回渲染和返回重定向,我会感到困惑。除了重定向,还有其他方法可以在不影响返回渲染的情况下重新加载页面吗?或者有没有办法在每次渲染后重新运行views.text_display() 函数?
关于项目:我正在创建一个打字练习程序,例如www.keybr.com
这是我的views.py文件:
from django.shortcuts import render
import os
import keyboard
def text_display(request):
char_no = request.session.get('char_no', -1) + 1
request.session['char_no'] = char_no
f = open(os.path.dirname(os.path.realpath(__file__)) + '\\text1.txt', "r+")
file_contents = f.read()
if char_no >= len(file_contents):
return render(request,'type/main.html',{"key_press":"Test is over"})
for line in file_contents:
for ch in line:
if keyboard.read_key() == file_contents[char_no]:
ctx = {'text': file_contents, 'key_press':'You pressed the right key.'}
f.close()
return render(request, 'type/main.html', ctx)# Here after returning the render I want to re run this view function. So, reloading looks like a possible thing to do.
else:
ctx = {'text': file_contents, 'key_press':'You pressed the wrong key.'}
return render(request, 'type/main.html', ctx)# Here after returning the render I want to re run this view function. So, reloading looks like a possible thing to do.
【问题讨论】:
-
你能给出一个你想在哪里做的示例视图吗?当您可以返回正常响应并且页面内容无论如何都会更新时,返回到同一页面的重定向似乎毫无意义?
-
@IainShelvington 我已经添加了 views.py 文件并描述了我想要的内容。随时要求澄清。我是 Django 新手,如果我做错了什么,请原谅我。
-
您每次按键都在调用您的视图?
keyboard.read_key()如何获得客户的键盘按键? -
是的,我在每次按键时都会调用我的观点
-
返回渲染后为什么不在下面文档的脚本标签中使用
window.location.reload();?这有什么害处?如果您希望此刷新发生,您甚至可以使用 Settimeout调用,让我们在某个时间后进行
标签: python django redirect reload