Django:未保存会话数据

时间:2016-04-10 02:01:42

标签: python django django-forms django-views django-sessions

非常对Web开发不熟悉,尝试使用会话将表单中的用户输入从一个视图传递到另一个视图。

会话似乎在我的“get_single_input”视图中的HttpResponseRedirect之后重置,因为我可以从会话中检索“local_test”。这在“single_output”视图中本地设置。

四处阅读,甚至尝试添加request.session.modified = True,但没有工作....

感谢您提前的时间。

from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import single_input

def get_single_input(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
       # create a form instance and populate it with data from the request:
        form = single_input(request.POST)

        if form.is_valid():
            # Iterate through the form cleaned data and add it to the session instance.
            for k , v in form.cleaned_data.iteritems():
                request.session[ k ] = v

            request.session[ "test" ] = "test"

            request.session.modified = True

            # Then redirect to the single_output page
            return HttpResponseRedirect( "/single_output/" )



    else:
        form = single_input()

    return render(request, 'single_design/input_page.html', {'form' : form })


def single_output(request):

    request.session[ "local_test" ] = "local_test"
    sess_value = request.session.values()

    for v in request.session.itervalues():
        variable.append(v)

    for k in request.session.keys():
        del request.session[ k ]

    return render(request, 'single_design/output_page.html', { "variable" : variable , "sess_value" : sess_value})

settings.py按要求

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '866e09kpk%a(k9&nrtk79#=54o_04)=9il=2r4b2etf4k#f!xm'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions', # This imports sessions for use 
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'single_design', # Importing my app
    ]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'primers.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'primers.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/London'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join( BASE_DIR , 'static' )

呈现输入表单的输入页面

{% extends 'single_design/base.html' %}
{% block content %}


    <body>

      <form action="/single_output/" method="post">
        {% csrf_token %}
        {{ form }}
      <input type="submit" value="Submit" />
      </form>

    </body>

{% endblock %}

输出页面,我遍历已附加会话项的列表。

{% extends 'single_design/base.html' %}
{% block content %}

    <body>
      this is the output page
    </body>

    {% for x in variable %}
      {{ x }}
    {% endfor %}

{{ sess_value }}
{% endblock %}

0 个答案:

没有答案