Django: any way to avoid querying for request.user on every request? -


for website pretty every page has header bar displaying "welcome, abc" "abc" username. means request.user called every single request resulting in database hits on , on again.

but once user logged in, should able store user instance in cookie , encrypt it. way can avoid hitting database repeatedly , retrieve request.user cookie instead.

how modify django this? there django plugins need?

thanks

you want use session middleware, , you'll want read documentation. session middleware supports multiple session engines. ideally you'd use memcached or redis, you write own session engine store data in user's cookie. once enable middleware, it's available part of request object. interact request.session, acts dict, making easy use. here couple of examples docs:

this simplistic view sets has_commented variable true after user posts comment. doesn’t let user post comment more once:

def post_comment(request, new_comment):     if request.session.get('has_commented', false):         return httpresponse("you've commented.")     c = comments.comment(comment=new_comment)     c.save()     request.session['has_commented'] = true     return httpresponse('thanks comment!') 

this simplistic view logs in "member" of site:

def login(request):     m = member.objects.get(username=request.post['username'])     if m.password == request.post['password']:         request.session['member_id'] = m.id         return httpresponse("you're logged in.")     else:         return httpresponse("your username , password didn't match.") 

Comments

Popular posts from this blog

Cursor error with postgresql, pgpool and php -

c# - how to write client side events functions for the combobox items -

ssh client with paramiko (python) -