I'm newbie in django and I was trying to construct a site in which the user can take a quiz. In a simpler version of that, I wanted just the questions to be displayed in random order, one after another(when the user presses a button) and when all the questions have been displayed to return to the main page, where there is a link "take the test". I know that it certainly isn't the most efficient way to do it, but I want to know what is wrong with my code.
urls.py:
path('start',views.startquiz,name='start'),
path('test/<int:pk>/<int:index>',views.TakeQuizView.as_view(),name='test'),
views.py:
def startquiz(request):
questions=list(Question.objects.all())
question=random.choice(questions)
pk=question.id
return redirect(reverse('quiz:test',args=(pk,1)))
class TakeQuizView(LoginRequiredMixin,View):
questions=list(Question.objects.all())
n=len(questions)
def get(self,request,pk,index):
question=Question.objects.get(id=pk)
self.questions.remove(question)
ctx={'question':question,'index':index,'n':self.n}
return render(request,'quiz/test.html',ctx,)
def post(self,request,pk,index):
if index<self.n:
question=random.choice(self.questions)
pk=question.id
return redirect(reverse('quiz:test',args=(pk,index+1)))
else:
self.questions=list(Question.objects.all())
return redirect(reverse_lazy('quiz:main'))
` Whenever I take the quiz for the first time, all works fine, and after all questions have been displayed, it returns to the main page. However, if I want to take the test again, the questions list fails to be filled up again and I get an error: list.remove(x): x not in list from remove()
I also tried to put in the get method the following code: `
if index==1:
self.questions=list(Question.objects.all())
` However it still does not work and I have some unexpected results. When I try to restart the quiz, I have the list filled up, and on the second step it suddenly gets emptied and I really cannot figure out what's going wrong.