Django会话丢失数据(空)

时间:2013-03-14 20:59:45

标签: django session-cookies

我想在我的网站中使用会话。我在settings.py文件中设置了以下设置:

 '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读取值时,会话为空... 可能是什么问题? 提前谢谢!

1 个答案:

答案 0 :(得分: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
            ...