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 :)
精彩评论