2013-03-14 205 views
0

我想在我的網站中使用會話。我設置了follwing設置在settings.py文件:Django會話丟失數據(空)

'django.contrib.sessions', #in the installed apps 

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' 

'django.contrib.sessions.middleware.SessionMiddleware', # in the midlleware classes 

視圖代碼

def apartamente(request): 
    form = SearchFormApartamente() 
    execute_form_process = 0 
    if request.method == 'POST': 
     form = SearchFormApartamente(request.POST) 
     execute_form_process = 1 
     request.session['apartamente'] = form 
     request.session['vasea'] = True 
     request.session.set_expiry(300) 
     request.session.modified = True 
    elif 'apartamente' in request.session: 
     form = searchFormApartamente(request.session['apartamente']) 
     execute_form_process = 1 

# forms.py 
class SearchFormApartamente(forms.Form): 
    thewidget = ColumnCheckboxSelectMultiple() 
    category = forms.ModelMultipleChoiceField(
     queryset=Categorie_Oferta.objects.filter(id__in=[1,2,3,4]), 
     required=False) 
    sector = forms.ModelMultipleChoiceField(queryset=Sector.objects.all(), 
     widget=forms.widgets.CheckboxSelectMultiple, required=False) 
    min_price = forms.IntegerField(required=False, 
     widget=forms.widgets.Input(attrs={'class': 'rounded'})) 
    max_price = forms.DecimalField(required=False) 

,但問題是,我嘗試在會話中以及何時存儲表單我第二次進入視圖並嘗試從sessiom讀取值,會話爲空... 可能是什麼問題? 在此先感謝!

+0

能否請您發表您的看法碼? – Brandon 2013-03-14 21:27:52

+0

爲了獲得會話,您必須將'get'放在'request.session.get('apartamente')'不是'request.session ['apartamente']'因爲這種格式用於存儲。總體來說@Brandon的回答是正確的。 – catherine 2013-03-15 11:10:30

回答

0

我會重新寫視圖代碼,如下所示,假設apartamente是窗體上的一個字段。

# I know it doesn't affect scoping, but I don't like having the view name 
# the same as a model or anything else for sanity 

def apartamente_view(request): 
    apartamente = request.session.get('apartamente', None) 
    form = SearchFormApartamente(request.POST or None, 
     initial={'apartamente': apartamente}) 

    execute_form_process = 0 
    if request.method == 'POST': 
     if form.is_valid(): 
      execute_form_process = 1 
      request.session['apartamente'] = form.cleaned_data['apartamente'] 
      request.session['vasea'] = True 
      request.session.set_expiry(300) 

      # do you really need this? 
      request.session.modified = True 
      ... 
+0

我用 「request.session.modified」 =真只是試圖迫使救......但我也就是事情是沒有必要存在... – Sergiu 2013-03-15 11:55:52

+0

好吧,有什麼錯誤? – Brandon 2013-03-15 13:54:01

+0

此代碼引發錯誤:實際上,第二行(表格= ...):_init __()獲得了關鍵字參數'data'的多個值。 – Sergiu 2013-03-15 14:09:26