Okay so I am very new to Django and relatively new to Python as well. In the website I am building, I am using some middleware that someone else made to keep track of "online" users using the cache to do so. Here is the middleware I'm referring to import datetime from django.core.cache import cache from django.conf import settings
class ActiveUserMiddleware:
def process_request(self, request):
current_user = request.user
if request.user.is_authenticated():
now = datetime.datetime.now()
cache.set('seen_%s' % (current_user.username), now,
settings.USER_LASTSEEN_TIMEOUT)
I want to take all of the online users, then divide them based on whether they are in highschool or college (which is an attributed I gave users via foreign key to a profile), and then return a random user from the list of online users who meet those certain requirements. I am at a loss on how to do this because the django structure is still confusing me. Would I implement this in a view or in a model? After looking at the code for the active_users app I have figured out that I can import the active_users, but I'm not sure if that is a list, an array, or an object. Also how do I determing the number of online_users? Does something like online_users.length
work? Here is the code I have come up with so far: (I have omitted some other imports and views for the sake of brevity). I'm sorry I haven't come up with a lot of code on my own, I am just very stuck/frustrated. Any help is greatly appreciated.
from online_status.status import CACHE_USERS
from online_status.utils import encode_json
from django.contrib.auth.models import User
from django.core.cache import cache
from django.template.context import RequestContext
def send_to(request):
sender = request.user
sender_level = sender.username
online_users = cache.get(CACHE_USERS)
match_users=[]
for User in online_users:
if User.username == sender_level:
match_users.append(user)
random_user = choice(match_users)
html = "<html> <body> <p> User: %s % random_user </p></body></html>" % random_user
return render_to_response(html)