在登录响应中将更多信息存储在Django会话中

时间:2018-03-03 21:26:59

标签: django django-authentication django-sessions

用户登录后,他们会在HttpResponse对象中发送session Cookie。我想添加一个额外的字段' foo'到会议,就像我做的那样

request.session['foo'] = 'bar'

以上操作无效,因为登录请求本身并没有会话对象,只有后续请求才有cookie。

另外,做

response.set_cookie("foo", "bar")

似乎没有将cookie与会话相关联(request.session [' foo']会在后续请求中抛出错误。)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果您考虑使用自定义登录视图,则可以执行以下操作:

def custom_login(request):
    if request.method == 'GET':
        if not request.user.is_authenticated
            # here, user is not logged in. 
            request.session['my_data'] = 'my value'

        return render(request, 'login.html' , {})
    elif request.method == 'POST':
        # get login credentials and authenticate user
        # see -> https://docs.djangoproject.com/en/2.0/topics/auth/default/#authenticating-users
        return HttpResponseRedirect('/homepage')

或者,如果要使用内置登录视图,则可以在中间件级别操作会话数据。只需编写一个这样的自定义中间件:

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        if request.path == '/login' and request.method == 'GET' and not request.user.is_authenticated:
            request.session['data'] = 123

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

并且不要忘记将此SimpleMiddleware添加到MIDDLEWARE中的settings.py列表中。您可以找到有关中间件here的更多信息。