I try to create a basic Q&A game. In the request.session['questions'] I am saving the questions I want to render .
The flow should be :
Question 1 as son the form is loaded --> once the user click next question 2 shoul be rendered an so on until the request.session['questions'] is empty.
whit the following code I Only could show the 2 first options and I don`t know why is not working as expected.
def game(request):
if request.method == 'GET':
request.session['questions'] = ['question1','question2','question3','question4']
print(request.session['questions'])
q = request.session['questions'].pop(0)
form = QForm({'question':q})
print(request.session['questions'])
return render(request, 'game.html', {'form':form})
else:
if request.method == 'POST' and len(request.session['questions']) >0:
q= request.session['questions'].pop(0)
print(name)
form = QForm({'question':q})
return render(request, 'game.html', {'form':form})
else:
return redirect('home')
CodePudding user response:
views.py
def game(request):
questions = ['question1','question2','question3','question4']
if request.method == 'POST':
answer = request.POST['answer']
questions = request.POST['questions']
q_list = questions[1:-1].replace('\'', '').split(',')
q_list.pop(0)
if q_list:
questions = q_list
else:
questions = None
context = { 'questions': questions }
return render(request, 'game.html', context)
game.html template:
{% if questions %}
<form action="{% url 'your:url' %}" method="post">
{% csrf_token %}
<label for="question">{{questions.0}}</label>
<input
id="answer"
type="text"
name="answer"
placeholder="Enter your answer..."
>
<input type="hidden" name="questions" value="{{questions}}">
<input type="submit" value="OK">
</form>
{% else %}
Game Over
{% endif %}