I want to refresh the page after returning a render. I can use return redirect to the same page, but I am confused if I can use both return render and return redirect in the same view function. Is there any other way to reload the page other than redirect without affecting the return render? Or is there a way to re-run the views.text_display() function after each render?
About the project: I'm creating a typing practice program like www.keybr.com
Here is my views.py file:
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.
Yes, a redirect can be used in the same view function. Here is an example
def index(request):
ctx = {}
# one in 3 chance to redirect
if random.randint(0, 2) > 1:
return redirect ('/')
return render(request, 'type/main.html', ctx)
Django redirect method returns a header[302] to the client, requesting a load to a new page. If you don't see the browswr refresh, it's because the browser didn't complete the request.