Reputation: 323
I'm creating a webapp in Django. I already run through Django tutorials from https://docs.djangoproject.com/en/dev/intro/ and part of documentation
I have a question how to store additional data between requests on the server-side. Django does it really cool with users as follows:
in views.py:
def login_user(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
now in another function you can use the information stored in back-end which is associated via csrf token like this:
in views.py
@login_required
def myappformmethod(request):
user = request.user
msg = 'hello '+user.username
the generated html file does not contain any direct information about the user which is logged, but it keeps the csrf token as a form field:
<form name="myform" action="/myapp/myappformmethod" method="post" onsubmit="prepare()">
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='NwKW2lFWSkkNEasdd3ExHe1l5ltzQi' /></div>
I would like to store some session-related data (e.g. favourite color) that will not be visible in html, but will be stored on server side and will be available using something like:
if request.favourite_color:
color = request.favourite_color
and not using
if request.POST.get('favourite_color'):
request.POST.get('favourite_color')
which is vulnerable to manual form element manipulation (if passed using form fields [type:hidden does not help, since you can edit them as well])
The aproriate approach would be adding field to request and producing something like "login" method mentioned earlier ... but how to do it?
Thanks!
Upvotes: 7
Views: 16385
Reputation: 11102
The feature you're looking for is called "sessions" and is supported by Django directly:
https://docs.djangoproject.com/en/dev/topics/http/sessions/
... and here are two examples from that page:
request.session['fav_color'] = 'blue'
fav_color = request.session['fav_color']
Upvotes: 12