Create and Retrive django session objects - django

I have customised the django default user table and used it for user signup and login. Now I need to create django session object to create a shopping cart (like that of an ecommerce website) which is user specific.How to create and retrive session objects in django??

Django provides full and built-in support for sessions (also anonymous sessions). First thing you need to enable the middleware session in the settings. Then you can easily retrieve the session as a dict in the views calling the request param at any point in your view.
def my_view(request):
# Get a param:
my_param = request.session.get('my_param'):
# Set a param:
request.session['my_param'] = True
# Some logic here ...
return HttpResponse('...')
Have a look at the docs here

Related

Django sessions for anonymous users

I want to be able to collect basic stats on the use of a webapp by users, both anonymous and logged-in.
The commonality here would be that using session ids, I could store data for both logged-in and logged-out users, and still be able to link the stored stats to a given session (who the session belongs to is immaterial).
However, I'm running into issues with collecting the session_key, as this does not appear to be set when an anonymous user enters the site (presumably because of the fact Django sessions are only saved when modified.
When I test a view with a logged-in user:
def create(request, *args, **kwargs):
print request.session.session_key
For a logged in user, the session_key is printed. For a logged out user or anonymous user this is None. On first request to the site, the session does not exist and consequently is not available to the view.
My current plan is to create a custom Middleware as a subclass of the official session middleware, but overriding process_request() to instantiate sessions for those who do not have one via session.save().
My only concern with this approach is that I'm not sure if it will have unforeseen consequences for other parts of Django - do people have any suggestions?
In a past project I did what you are suggesting but just within a view where I needed to use session_key for unauthenticated visitors. It did not cause any problems in my project:
if not request.session or not request.session.session_key:
request.session.save()
# request.session.session_key now set
You can choose to save session every request by setting:
SESSION_SAVE_EVERY_REQUEST = True
This force django to assign the session key for each session
https://docs.djangoproject.com/en/2.1/topics/http/sessions/#when-sessions-are-saved

How to use cookies and sessions django

I a have a certain amounts of products. I want to make function that save a certain products in cookies not database. But i dont know how to create a list of product in cookies. Products mast be saved in such way from that i can show them by some function. What method i must use to create a list of products in cookies.
def add_instance_note(request,instance_id):
instance = Instance.objects.get(pk=instance_id)
request.session['list'].append(instance_id)
return render_to_response('show_instance.html', locals(),
context_instance=RequestContext(request))
def show_instance_note(request):
instances=[]
for instance_id in request.session['list']:
instances.append(Instance.objects.get(pk=instance_id))
return render_to_response('show_instance_note.html', locals(),
context_instance=RequestContext(request))
To use sessions with Django you must first enable and configure a session service, with a certain backend (in your case cookies). This is covered in depth here:
https://docs.djangoproject.com/en/1.6/topics/http/sessions/#using-cookie-based-sessions
For basic cookie support, this is available on the request/respond objects:
https://docs.djangoproject.com/en/dev/ref/request-response/
You can set a cookie with set_cookie:
def GetHandler(request):
response = HttpResponse('Testing cookies')
response.set_cookie('key', 'value')
To get cookies, you retrieve them from request.COOKIES. You can use standard dict operations like has_key and get to retrieve them (by the key you set previously).

How to create a session extra when login through django admin?

In a view I can do the following: request.session ["mysession"] = mysession. But I do not want to use a view, I want to create my session during login with the admin of django. Obviously, without overwriting the framework of django
Is this possible?
Should AdminAuthenticationForm overwrite or the view that processes this form to add my session?

django- how to have a common list for anonymous and logged in user

i have a list on my website which remains same for both anonymous and logged-in users. I use session dictionary to store the data.But when I logout I lose the session values as the django.contrib.auth.views.logout uses session.flush().....If I make a custom logout by removing the sessions.flush() ,I am not able to log-out. Can someone tell me how override the flush()..or some other by which we can create a common list for anonymous and logged-in users.
Lets say you have a list called 'user_list'
def logout_view(logout):
# Do whatever pre conditions you have here.
my_list = request.session['user_list']
logout(request)
# Now Django would have flushed your previous sessions and created a new session.
request.session['user_list'] = my_list
return HttpResponse() # Or render to response i.e whatever you do.
Now make sure that a session is being created for anonymous user also. And rest everything will work. Hope it does for you.

How can I detect multiple logins into a Django web application from different locations?

I want to only allow one authenticated session at a time for an individual login in my Django application. So if a user is logged into the webpage on a given IP address, and those same user credentials are used to login from a different IP address I want to do something (either logout the first user or deny access to the second user.)
Not sure if this is still needed but thought I would share my solution:
1) Install django-tracking (thankyou for that tip Van Gale Google Maps + GeoIP is amazing!)
2) Add this middleware:
from django.contrib.sessions.models import Session
from tracking.models import Visitor
from datetime import datetime
class UserRestrictMiddleware(object):
"""
Prevents more than one user logging in at once from two different IPs
"""
def process_request(self, request):
ip_address = request.META.get('REMOTE_ADDR','')
try:
last_login = request.user.last_login
except:
last_login = 0
if unicode(last_login)==unicode(datetime.now())[:19]:
previous_visitors = Visitor.objects.filter(user=request.user).exclude(ip_address=ip_address)
for visitor in previous_visitors:
Session.objects.filter(session_key=visitor.session_key).delete()
visitor.user = None
visitor.save()
3) Make sure it goes after the VisitorTrackingMiddleware and you should find previous logins are automatically bumped when someone new logs in :)
If you're already using django-tracking as suggested here, there's a much easier way to implement this:
Define a signal handler:
# myapp/signals.py
def kick_my_other_sessions(sender, request=None, user=None, **kwargs):
from tracking.models import Visitor
from django.contrib.sessions.models import Session
keys = [v.session_key for v in Visitor.objects.filter(user=request.user).exclude(session_key=request.session.session_key)]
Session.objects.filter(session_key__in=keys).delete()
Create a listener for the user_logged_in signal:
# myapp/__init__.py
from myapp.signals import kick_my_other_sessions
from django.contrib.auth.signals import user_logged_in
user_logged_in.connect(kick_my_other_sessions, sender=User)
This will institute a sort of "last user to login wins" system. If you want to allow multiple logins by the same user from the same ip, you can add an .exclude() to the Visitors lookup.
Django's middleware will probably help you achieve this. The issue is that you will probably want to allow multiple anonymous sessions from the same IP address, even authenticated sessions for different users, but not authenticated sessions for the same user.
You'll want to:
Create a user profile model to store the IP address of a user's last login. See Django's Storing additional information about users documentation.
Implement a custom authentication backend. This backend, when triggered and successfully authenticating a user (just call super) would wipe out the user's last login IP in the profile model.
Implement a subclass of Django's django.contrib.sessions.SessionMiddleware class. Implement process_request. If the request.user object's profile model has no IP address, set it and allow the request. If it has an IP, and the IP is different from the current request's IP (request.META.REMOTE_ADDR), then do whatever you like to either log out the other user, or return an error to the requestor.
Update your settings.py file so that your custom auth backend is processed first, and so that your custom session middleware is also processed first. This involves updating settings.AUTHENTICATION_BACKENDS and settings.MIDDLEWARE_CLASSES.
You'll need to do this with custom middleware.
In your middleware process_request() method you will have access to the request object so you can do something like the following:
session_key = request.session.session_key
ip_address = request.META.get('REMOTE_ADDR', '')
Now you know the IP address, so check a model you create that (roughly) would look like this:
class SessionIPS(models.Model):
session = models.ForeignKey(Session)
IP = models.CharField(max_length=20)
So when a session is created or deleted you will modifiy your session ip's table accordingly, and when a request comes in make sure the IP address isn't being used for another session. If if is, then return a Http404 (or something like it) from the middleware.
A pluggable app that can show you a lot more detail (and even includes IP address in its own model) is django-tracking.