1

我想在我的站点中使用会话。我在 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 读取值时,会话是空的......可能是什么问题?提前致谢!

4

1 回答 1

1

我将重写视图代码,如下所示,假设这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
            ...
于 2013-03-15T11:02:29.507 回答