为啥 Django 不退出会话? .get 函数也不再像 .all 函数那样亮起?数据库中没有显示任何内容
Posted
技术标签:
【中文标题】为啥 Django 不退出会话? .get 函数也不再像 .all 函数那样亮起?数据库中没有显示任何内容【英文标题】:Why is Django not pulling from session? Also .get funtion no longer lights up as the .all function does? Nothing displays from database为什么 Django 不退出会话? .get 函数也不再像 .all 函数那样亮起?数据库中没有显示任何内容 【发布时间】:2021-04-26 15:22:26 【问题描述】:
`from django.shortcuts import render,redirect, HttpResponse`
`from user_login_app.models import User`
`from .models import Book,Author,Rating`
`from django.contrib import messages`
def index(request):
`user=User.objects.get(id=request.session['user_id'])`===================================================On this line the get function isn't operating I can no longer pull from session and the function doesn't light up the way it did. I also get no user display on the page. Normally the .get function highlights as the .all function does, also displays the logged in user on the page. No I get nothing from Session. To be clear, I also made all migrations. I have items in my database. I just can't pull them out. As I have in the past.
`author=Author.objects.all()`
`rating=Rating.objects.all()`My context statment no longer renders anything. I double checked it agianst past projects. those were all written very similarly.
`context=`
`'users':user,`
`' authors':author,`
`'ratings':rating,`
return render(request,'book_home.html',context)
我不明白为什么我的 .get 函数不起作用?我希望有人能解答这个谜题。
【问题讨论】:
您好,欢迎来到 *** 社区;请阅读此帮助页面以提出更好的问题。请分享您遇到的错误并多加注意添加一个sn-p;例如,您可以在发布问题之前查看问题的预览。 ***.com/help/how-to-ask 【参考方案1】:你可以试试这个:
from django.contrib.sessions.models import Session
session = Session.objects.get(session_key=request.session.session_key)
user_id = session.get_decoded().get('_auth_user_id')
user = User.objects.get(pk=user_id)
.....(rest of your code and context)
return ......
我没有测试代码,这里你可以看看https://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/,
【讨论】:
以上是关于为啥 Django 不退出会话? .get 函数也不再像 .all 函数那样亮起?数据库中没有显示任何内容的主要内容,如果未能解决你的问题,请参考以下文章
为啥 Django 不在 Varnish 代理后面生成 CSRF 或会话 Cookie?