2009-12-22 136 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