Reputation: 3075
I am using login middleware to create a user login form.
What is the best method to retrieve user id from view, after user successfully login?
Created a middleware.py:
class LoginMiddleware(object):
def process_request(self, request):
if request.path != self.require_login_path and request.user.is_anonymous():
if request.POST:
return login(request)
else:
return HttpResponseRedirect('%s?next=%s' % (self.require_login_path, request.path))
Upvotes: 0
Views: 4230
Reputation: 239200
Once a user has logged in, their associated User
object is available via request.user
in your template, automatically. When you say "user id", I'm not sure if you mean username or the literal value of id
in the database. The same method applies for both, though: {{ request.user.username }}
or {{ request.user.id }}
.
Additionally, as the commenter above noted, there's no reason to create a new authentication middleware unless you need to change something in how the login is processed. Otherwise, leave it alone and use the default. (Which seems to be what you should be doing based on your middleware).
UPDATE: Neglected to mention that in order to access request.user
in your template, you must pass in RequestContext
. Example render_to_response
below:
from django.template import RequestContext
render_to_response('templates/mytemplate.html', {}, context_instance=RequestContext(request))
Upvotes: 5