【问题标题】:Django Sessions not Working on remote serverDjango 会话不在远程服务器上工作
【发布时间】:2022-01-05 03:52:34
【问题描述】:

我正在尝试在我的 django 应用程序中使用会话变量

view.py

def get(self, request):
    room_name = request.session.get('room_name')
    context = app.get_context(room_name)
    context['room_name_create'] = room_name
    context['room_name_check'] = request.session.get('room_name')
    return render(request, self.template, context)

js

console.log('a', context.room_name_create)
console.log('b', context.room_name_check)

这在我的本地服务器上完美运行。

在远程服务器上 context.room_name_create 显示一个值,但 context.room_name_check 在浏览器中显示为 null

这只是一个小应用程序,我已将所有源文件复制到远程服务器,因此所有源文件都是相同的。我已经在不同的浏览器上测试过这个

我已经在 shell 中运行了 Django tutorial 中的示例,它运行良好

谁能建议我可以检查什么来解决这个问题?

【问题讨论】:

  • 你在哪里设置会话变量?像request.session.set('room_name') = some_value 这样的行定义在哪里?
  • 我没有这样的台词。我不在本地服务器上使用它,也无法在 django docs 中看到它 - 它只有 get 选项 - 具有默认值
  • 您也可以像这样设置会话变量:request.session['room_name'] = "foo"。你不需要二传手。
  • 是的——就是这样——你想把它作为答案发布吗?

标签: django session


【解决方案1】:

要在 Django 中使用会话,您通常需要做两件事:

在会话中设置数据

在您的情况下:room_name = request.session.set('room_name') = some_valueroom_name = request.session['room_name'] = some_value

从会话中获取数据

在你的情况下:room_name = request.session.get('room_name')

注意:您需要先在会话中设置数据,然后再尝试检索它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2015-12-08
    • 2017-04-07
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    相关资源
    最近更新 更多