简体   繁体   中英

Django get objects one by one to render in a template

I'm creating an quiz app, where the user answers questions one by one, For example when user answer the question and press submit it will provide the next question for the user to be answered.. How it is done in django function based views by getting objects one by one and return to a template and then the next object until the last object??

models.py

class Quiz(models.Model):
    question = models.TextField(max_length=250)

class Choice(models.Model):
    question = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='main_question')
    choice = models.CharField(max_length=100)
    is_true = models.BooleanField("This is Correct answer",default=False)
views.py
def quiz_question(request):
    question = Quiz.objects.get(id=1)
    choices = Choice.objects.filter(question_id=1)
    context = {
        "question":question,
        "choices":choices
    }
    return render(request,"quiz/display_question.html",context=context)

This isn't something that you can accomplish in a purely backend approach. Django is generating a page and sending it to the user.

You could include all questions in a single page, and give all but the first question the css attribute display: hidden . This means the user could see all the questions with access to nothing other than developer tools, and is typically a bad idea unless your reason for doing this for no reason other than aesthetics.

If you want to display a single question to the user in a long list in a reasonably secure manner, you need to add some logic to the backend that stores what question they're on. When they complete a question, that answer is stored, and the view checks what the next question is and returns that to them. Continue this loop until there's no questions left in the list.

Once that happens, you'll go to a new view that displays the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM