Same random record across website
I am building a website that shows a different background every time a user enters it. This background is then used across the website with the same user and session.
So basically, a user entres the homepage, gets a background and that image won't change until the user closes the website or opens up a new page. I think you understand what I mean.
I know how to get a random record from the database using Django, but I'm not sure how to keep that record persistent across the website, because if I pull it on every view, I'll get a different image on different pages.
So my "index" view could be calling
bgimage = BackgroundImage.objects.random()
But then I have a problem.开发者_如何学运维 How can I get this random record unchanged across all the other views. Is that possible? Should I be looking into sessions, cookies?
Thank you!
you could use sessions - something like
if 'bgimage' not in request.session:
bgimage = BackgroundImage.objects.random()
request.session['bgimage'] = bgimage.pathtoimage
Context processor:
def bgimage(request):
if 'bg_image' not in request.session:
image = BackgroundImage.objects.random()
request.session['bg_image'] = image.file
return {'background_image' : request.session['image']}
精彩评论