简体   繁体   中英

The session variable is lost, in Django

In a system that should be multi-company, I use context_processors.py to load company options, by selecting from the sidebar. The user can change companies at any time.

When the user selects a company, the option is recorded in a session variable.

It happens that when the user changes pages, the information of the session variable is lost.

What am I doing wrong or failing to do? Is there a better way to do this?

Relevant code snippets follow:

context_processors.py

from apps.client.models import Client

def units (request):
    # Dictionary with business options
    clients = Client.objects.values ​​(
        "client_id",
        "company_id__name",
    )
    clients_list = []
    for client in clients:
        clients_list.append (
            {
                'client_id': client ['client_id'],
                'name': client ['company_id__name']
            }
        )
    return {'clients_list': clients_list}

base.html

# System base page.
# Displays the list of business options.
<select class = "form-control select2">
<option value = "{{request.session.unit_id}}"> {{request.session.unit_id}} </option>
{% for client in clients_list%}
<option value = "{{client.client_id}}"
{% if request.session.unit_id == client.client_id%}
selected
{% endif%}>
{{client.client_id}}
</option>
{% endfor%}
</select>
...

# Whenever a company is selected ...
<script>
$ ("# select_unit"). click (function () {
    var option_id = $ (this) .val ();
    var url = "{% url 'home: set_unit'%}";
    $ .ajax ({
        type: "GET",
        url: url,
        data: {'unit_id': option_id},
        success: function () {}
    });
});
</script>

view.py

# View that registers the variable in the session.
def set_unit (request):
    unit_id = request.GET.get ("unit_id")
    request.session ['unit_id'] = unit_id

settings.py

MIDDLEWARE = [
    'apps.core.middleware.AppMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_globals.middleware.Global',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
                'apps.home.context_processors.units',
            ],
        },
    }
]

Your view that's setting a session variable needs to return a response. Since you're calling it with Ajax, a JsonResponse with simple {'status': 'ok'} dictionary is fine. Add this line at the end of set_unit :

return JsonResponse({'status': 'ok'})

If you look at your browser dev tools network tab or in your console you'll see that currently your request is generating an error since a view should not return None . That's the reason the session isn't saved and the new state of the session variable not persisted.

I think the problem is that u didn't set that the session was modified, after change the session value.

request.session.modified = True

Another option is add in your settings.py:

SESSION_SAVE_EVERY_REQUEST=True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM