I am using this code to validate logged in / authenticated users in my views.py.
@login_required
def my_view(request, username):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise Http404(u'User not Found')
if user == request.user and request.user.is_authenticated():
variables = RequestContext(request, {})
return render_to_response('my_template.html', variables)
is there another way (ie less code) to validate users, or do I need to put that in every view?
request.userwithlogin_requiredis the current logged-in user, you don’t need to check it again by username, and thus there is no need to checkis_authenticated. If you just want to render a page which have different logic for different user type, try the code below, if not, just userequest.user. Also, useget_object_or_404andrendershortcuts.