2009-12-22 133 views
5

我一直在努力工作数小时,试图了解以下问题:我有一个用户发送Ajax请求来动态发送表单并记录提交时读取的表单数量增加。为此,我使用request.session['editing_foo'] = { 'prefix_of_form_elements' : pkey },以便我可以将它们与数据库相关联进行保存和加载(-1代表尚未保存的新表单)。Django会话持续但丢失数据

然而,当我用下面的代码(参见下图)我得到以下奇怪的输出:

1日点击:

{} foousername 
next_key 1 
1 
{u'1-foo': -1} 

第二点击:

{} foousername 
next_key 1 
1 
{u'1-foo': -1} 

第三请求:

{} foousername 
next_key 1 
1 
{u'1-foo': -1} 

这是怎么回事?

id_fetcher = re.compile(r'\d') 


@login_required 
def ajax_add_foo(request): 
    def id_from_prefix(key): 
     return int(id_fetcher.search(key).group(0)) 

    if 'editing_foos' not in request.session: 
     print "reinitializing" 
     request.session['editing_foos'] = {} 

    print request.session['editing_foos'], request.user 
    keys = request.session['editing_foos'].keys() 
    if len(keys) == 0: 
     next_key = 1 
    else: 
     print [ id_from_prefix(key) for key in keys ] 
     next_key = max([ id_from_prefix(key) for key in keys ]) + 1 
    print "next_key", next_key 

    fooform = FooForm(prefix=next_key) 
    print next_key 

    request.session['editing_foos'].update({create_prefix(FooForm, next_key) : -1 }) # This quote is new and has no pkey 
    print request.session['editing_foos'] 

    return render_to_response('bar/foo_fragment.html', 
           {'fooform' : fooform, }, 
           context_instance=RequestContext(request)) 

非常感谢大家!

注意:这是关于相同源代码的previous question的后续处理。

回答

11

我不认为我完全理解这个问题,但你可能想看看你使用

在这​​如果你使用的缓存会话引擎,你需要确保你有缓存设置正确(例如虚拟缓存会抛出会话数据)

另一种可能性是您的会话未保存,因为您没有更改会话,您正在更改可变对象存储在会话中。你可以尝试forcing the session to save加入这个地方在你的看法:

request.session.modified = True 
+0

漂亮!你是个天才!我从来没有在文档中看到提及这个选项! – SapphireSun 2009-12-22 19:19:27

+0

你救了我的命!没有看到在文档 – 2014-03-15 01:34:45

+0

Thanx兄弟..!你节省了我的日子:P – 2014-06-26 08:05:14