I made a Custom template tag using this doc like this in my Django application :
myproject/
__init__.py
models.py
templatetags/
__init__.py
myCustomTags.py
views.py
in the myCustomTags.py
, I need to use some variables that there are in views.py
so I save those variables in session , and tried to get them in myCustomTags.py
, but noting worked and it does not recognized my sessions.
I used this doc ,but it seems that this method wants me to use session_keys. in this method my question is that how to use the sessions without the key or somehow pass the keys from views.py to myCustomTags.py
too .
here is my code in this method:
views.py:
from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
from django.contrib.sessions.backends.db import SessionStore
my_session = SessionStore()
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
# some process to validate and etc...
my_session['test_session'] = 'this_is_my_test'
my_session.create()
return redirect(reverse('basic_app:index'))
myCustomTags.py
from django import template
from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
from django.contrib.sessions.backends.db import SessionStore
my_session = SessionStore()
register = template.Library()
@register.simple_tag
def userStatusMode():
status = my_session['test_session']
return status
base.html:
{% load dynamic_vars %}
{% userStatusMode as user_status_thing %}
<!-- and somewher in base.html -->
{{user_status_thing}}
the other method was to use requst.sessions in views.py and try to get them in myCustomTags.py that didn't worked too.
by the way , how can I use session outside of the views ? am I missing something here ?
This is all kinds of wrong.
You're not supposed to instantiate SessionStore directly. The way you've done it, you haven't given any indication of which user's session you are trying to get or set.
Instead you are supposed to access the session for the current user via request.session
.
request.session['test_session'] = 'this_is_my_test'
and similarly in the template, where you can directly access the session dict (no need for a template tag):
{{ request.session.test_session }}