Monday, January 30, 2017

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

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b27645bb-2073-4b8f-ac39-6d05d6cc2122%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment