如何在两个视图之间传递一组对象?

时间:2020-08-24 14:33:53

标签: python django

我正在构建一个测验应用程序,其中通过创建模型类将问题存储在数据库中。我正在从数据库中为每个用户检索一个随机问题集,然后将其呈现在HTML页面上。问题是登录用户后,会出现随机的问题集,但刷新页面后该随机集会丢失。 我该如何解决 我想到的一件事是在登录用户并将其作为字典传递给另一个视图之后检索另一个视图中的对象集。 但是我找不到语法或任何函数(如果存在)。请帮忙。 我正在使用django 3.1和MySQL作为数据库。 我的views.py看起来像这样:

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})

2 个答案:

答案 0 :(得分:2)

实际上并没有直接方法在args或kwargs之类的视图之间传递值。我建议使用请求会话来存储值并再次访问它们。

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)

答案 1 :(得分:0)

您可以使用request.session来第一次存储您的问题ID:

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})