开发者

Session management for unauthenticated users

开发者 https://www.devze.com 2023-03-13 16:41 出处:网络
I have a strange question about session management. I implemented a form chain and after forms are completed a model is saved to database but that model has fields like create_user, update_user and s

I have a strange question about session management.

I implemented a form chain and after forms are completed a model is saved to database but that model has fields like create_user, update_user and so on.

In order to fill these user fields,of course, there should be an authenticated user.However, my form chain can be filled by anonymous user, as well.

If that anonymous user registers or logins to the system before his session flushs, his user_id should be assigned to create_user开发者_开发知识库 and update_user fields..

What is the best way to implement such system ?

I hope I explain the situation.

Thanks


When your model is saved save the model instance to a list in your session, for example:

views.py:

...
form = DataForm(request.POST)
if form.is_valid():
    instance = form.save()
    instances = request.session.get('filed_instances', [])
    instances.append(instance)
    request.session['filed_instances'] = instances

in your login method after logging in (depends on your implementation offcourse) you can update these as follows:

instances = request.session.get('filed_instances')
if instances:
    for instance in instances:
        instance.create_user = request.user
        instance.update_user = request.user
        instance.save()


Put your logged in username in a session variable. At session start, if that variable is not set, set it to an empty string, null or any other value which represent to you an anonymous user. Than, when saving data in a database, use that name as creation/update username. I hope it was helpful :)

0

精彩评论

暂无评论...
验证码 换一张
取 消