user3234810
user3234810

Reputation: 482

Django : Session data not being saved

Extremely new to web development, trying to pass user inputs in a form from one view to another using the session.

Session seems to reset after the HttpResponseRedirect in my "get_single_input" view, as I can retreive the "local_test" from the session. This set locally within the "single_output" view.

Read around and have even tried adding request.session.modified = True but not working....

Thank you for your time in advance.

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 as requested

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' )

Input page that renders the input form

{% 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 %}

Output page where I loop through the list that i have appended session items to.

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

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

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

{{ sess_value }}
{% endblock %}

Upvotes: 0

Views: 4396

Answers (1)

Abhinav
Abhinav

Reputation: 682

I can think of only one scenario - that your form is never valid. So the condition where you check form.is_valid() is always failing.

Try setting the test key before that:

form = single_input(request.POST)
request.session['test'] = 'test'
if form.is_valid():
    ...

Upvotes: 2

Related Questions