我已经根据this在Django中扩展了会话。简而言之,我添加了一个名为ul.bar_tabs>li.active {
margin-top: -17px;
}
的字段来保存会话所属用户的用户ID。
一切正常,但我添加的自定义字段account_id
未在登录时设置。为此:
account_id
我已尝试将以下内容添加到from django.contrib import auth
from MyApp.models import CustomSession
def login(request):
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
try:
auth.login(request, user)
session_key = request.session.session_key
# CODE HERE
if session_key is not None:
return HttpResponse(json.dumps({'status': 'Success'}))
else:
return HttpResponse(json.dumps({'status': 'Fail'}))
。但是,它们都没有奏效:
CODE HERE
request.session.model.account_id = user.id
session = CustomSession.objects.get(pk=session_key)
session.account_id = user.id
session.modified = True
request.session.account_id = user.id
在每次尝试中,request.session[account_id] = user.id
在数据库中都是account_id
。
我在这里缺少什么?
答案 0 :(得分:2)
如果要在会话表中提供自定义名称或创建自定义字段,可以按照以下步骤操作。
定义自定义会话后端:
my_project
my_project/
settings.py
session_backend.py
...
user/
models.py
...
from django.contrib.sessions.backends.db import SessionStore as DBStore
import user
class SessionStore(DBStore):
@classmethod
def get_model_class(cls):
return user.models.MySession
def create_model_instance(self, data):
"""
overriding the function to save the changes to db using `session["user_id"] = user.id` .
This will create the model instance with the custom field values.
When you add more field to the custom session model you have to update the function
to handle those fields as well.
"""
obj = super().create_model_instance(data)
try:
user_id = data.get('user_id')
except (ValueError, TypeError):
user_id = None
obj.user_id = user_id
return obj
然后在 settings.py
中导入您的自定义类
SESSION_ENGINE = "my_project.session_backend"
在应用中的 models.py
中定义自定义模型说 user
from django.contrib.sessions.models import Session
class MySession(Session):
# you can also add custom field if required like this user column which can be the FK to the user table
user = models.ForeignKey('user', on_delete=models.CASCADE)
class Meta:
app_label = "user"
db_table = "my_session"
现在运行以下命令进行迁移
python manage.py makemigrations
python manage.py migrate
完成:)
答案 1 :(得分:1)
您错过了CustomSession是模型的事实;你需要保存实例,而不是设置"修改"就像你在版本2中一样。
session = CustomSession.objects.get(pk=session_key)
session.account_id = user.id
session.save()