简体   繁体   中英

How to pass a set of objects in between two views?

I'm building a quiz app in which I'm storing questions in the database by creating a model class. I am retrieving a random question set for each user from the database and then rendering them on an HTML page. The problem is after logging a user in, a random set of questions appears but that random set is lost after refreshing the page. How do I solve this One thing that I thought was retrieving the object set in another view....say after logging a user in and passing it as a dictionary to another view. But I can't find the syntax or any function (if it exists). Please help. I'm using django 3.1 and MySQL as my database. My views.py looks like this:

from django.shortcuts import render, redirect
from .models import *
from .forms import UserForm
from django.contrib.auth.forms import AuthenticationForm
import random
from django.contrib.auth import login, logout, authenticate

# Create your views here.
def home(request):
    return render(request, 'testapp/home.html')

def loginuser(request):
    #form = UserForm()
    if request.method == 'GET':
        form = AuthenticationForm()
        return render(request, 'testapp/login.html', {'form':form})
    else:
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
        if user is None:
            return render(request, 'testapp/login.html', {'form':AuthenticationForm(), 'error':'Username or password incorrect'})
        else:
            login(request, user)
            return redirect('paper')

def paper(request):
    #objects = Questions.objects.all()
    """count = Questions.objects.all().count()
    slice = random.random() * (count-5)
    objects = Questions.objects.all()[slice:slice+5]"""
    #objects = {{ objects }}
    objects = Questions.objects.all().order_by('?')[:5]
    return render(request, 'testapp/paper.html', {'objects':objects})

There isn't really a direct way to pass values between views such as args or kwargs. I would recommend using the request session to store values and access them again.

def paper(request):
    question_set = Questions.object.all()
    question_set = question_set.order_by('?')[:5]

    # Retrieve the primary keys from the 5 questions selected.
    question_pks = question_set.values_list('pk', flat=True)
    # Store the pks in a list on the request session.
    request.session['question_ids'] = list(question_pks)

    context_data = {'objects': question_set}
    return render(request, 'testapp/paper.html', context_data)


def home(request):
    # Get all the pks from the request session again.
    question_pks = request.session['question_ids']
    # Use the pks to retrieve the same question objects from the database.
    question_set = Questions.objects.filter(pk__in=question_pks)

    context_data = {'objects': question_set}
    return render(request, 'testapp/home.html', context_data)

You can make use of request.session to store your questions ids the first time :

def paper(request):
    if 'question_ids' not in request.session:
        request.session['question_ids'] = list(Questions.objects.all().order_by('?').values_list('id', flat=True)[:5])
    objects = Questions.objects.filter(id__in=request.session['question_ids'])
    return render(request, 'testapp/paper.html', {'objects':objects})

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