我正在开发一个应用程序,用户可以在其中选择一个类别,该类别将返回该类别的随机选择。我试图实现的主要功能是一旦选择了一个项目,就不能再在会话中随机选择它。
例如,我们有3类照片:风景,城市和肖像,每张照片有5张。用户选择城市,然后重定向到具有来自城市类别的随机照片的详细信息页面。他可以刷新页面或单击按钮从该类别中获取新照片。当该类别没有新照片时,他被重定向回家。
通过将查询集转换为列表,我可以从所选类别中获取我的随机项,但数据不会持久存在。每次刷新我重置的列表,因此先前选择的照片可以再次出现,忽略了我在选择后从列表中删除了该项目的事实。
这是views.py,其功能负责:
def randomPhoto(request, pk, **kwargs):
# queryset to get all photos from selected category
gallery = list(Photos.objects.filter(id=pk)
.values_list("partof__category", flat=True))
# select random photo from list
last = len(gallery) -1
randomInt = random.randint(0, last)
randomPic = gallery[randomInt]
gallery.remove(randomPic)
if len(gallery) == 0:
return render(request, 'gallery/category_select.html')
photoDetails = {
'category' : Category.objects.get(id=pk),
'author' : Author.objects.get(tookin__category=randomPic),
'uploadedPhoto' : 'http://localhost:8000/media/' +
str(Photo.objects.get(category=randomPic).photoUpload),
'randomPic' : randomPic,
}
return render(request, 'gallery/random_photo.html', {'photoDetails': photoDetails})
我正在寻找的功能是(其中每个数字是列表中的对象/项目):
我相信我的问题在于必须配置会话或cookie以使数据在匿名会话中保持不变。最后我将添加一个用户模块,这样每个用户都会保存他们的浏览历史记录,但现在我希望它能够像匿名用户一样工作。
我尝试将SESSION_SAVE_EVERY_REQUEST = True
添加到settings.py
并将request.session.modified = True
放入我的views.py
,但我怀疑我正在正确实施它们。我已经阅读了关于会话和cookie的一些SO问题,但是无法找到适合我的问题的东西。 Django Sessions Doc似乎很有趣,但势不可挡。我不知道从哪里开始尝试将会话方面连接在一起。
我想知道是否有一种简单/ Pythonic方式来实现我的网络应用程序从列表中给我一个非重复项目,直到会话中没有任何内容。
您的问题是您的变量不会从一个请求转移到下一个请求。执行此操作的最佳方法是使用request.session = ...
设置变量,然后稍后检查并执行操作。下面是一个示例,您可以根据自己的喜好进行扩展:
import random
from django.shortcuts import redirect
class TestView(View):
def get(self, request, *args, **kwargs):
gallery = request.session.get('gallery', None)
if (type(gallery) is list) and (len(gallery) == 0): # When list is empty, clear session & then redirect
del request.session['gallery']
request.session.modified = True
return redirect('<your_redirect_url>')
if gallery is None: # If first visit to page, create gallery list
gallery = list(models.Photos.objects.all().values_list("partof__category", flat=True))
# select random photo from list
last = len(gallery) -1
randomInt = random.randint(0, last)
randomPic = gallery[randomInt]
gallery.remove(randomPic)
request.session['gallery'] = gallery
return render(request, 'test.html', {})