我正在构建一个测验应用程序,通过创建一个模型类将问题存储在数据库中。我从数据库中检索每个用户的随机问题集,然后将它们呈现在HTML页面上。问题是,在用户登录后,会出现一组随机问题,但在刷新页面后,这组随机问题就会丢失。在登录用户并将其作为字典传递给另一个视图之后,我认为如何解决在另一个view....say中检索对象集的问题。但是我找不到语法或任何函数(如果存在的话)。请帮帮忙。我使用Django3.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})发布于 2020-08-24 22:45:36
在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)发布于 2020-08-24 22:41:41
您可以在第一次使用request.session存储您的问题ids:
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})https://stackoverflow.com/questions/63563138
复制相似问题