How to set a custom field in a Django session model?

133 views
Skip to first unread message

Utku Gültopu

unread,
Jan 30, 2017, 3:59:06 PM1/30/17
to Django users
I have extended the session in Django per [this][1]. In short, I have added a field named `account_id` to hold the user id of the user which the session belongs to.

Everything works fine, except the custom field `account_id` I have added is not being set on login. To do so:

    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'}))

I have tried putting the following to `CODE HERE`. However, none of them worked:

1. `request.session.model.account_id = user.id`

2.
        session = CustomSession.objects.get(pk=session_key)
        session.account_id = user.id
        session.modified = True
3. `request.session.account_id = user.id`
4. `request.session[account_id] = user.id`

In each of these attempts, `account_id` is `NULL` in the data base.

What am I missing here?

  [1]: https://docs.djangoproject.com/en/1.10/topics/http/sessions/#example
Reply all
Reply to author
Forward
0 new messages