I’m writing a simple auth system to login (and logout) users. The username is an email address, which looks up an email field.
I’m using:
user = User.objects.get(email__exact=email)
# if user obj exists
if user:
# if authenticate
if authenticate(user, email, password):
# create session
request.session['user'] = user
# redir
return HttpResponseRedirect('/home/')
else:
return HttpResponseRedirect('/home/login/')
# no user obj found? (no email found actually)
else:
# redir
return HttpResponseRedirect('/home/')
to find if a user exists, however if a user is not found Django throws an error:
User matching query does not exist.
All I want to do is see if that query matches a result. How do I count rows?
I think this is probably more what you want:
Personally I think that’s cleaner than Ignacio’s method, but it’s a matter of taste really.
Finally, the last part of your question (“How do I count rows?”):
getonly ever returns an object, and raises an exception if no objects match the criteria you passed in, or if multiple objects match the criteria. To get the number of objects in aQuerySet, you can just calllenon it:Or, call
count():The former method (
len) will be quicker if you’ve already evaluated theQuerySet(since it’s just counting the number of items in a list, effectively); the latter (count()) will be faster if you’ve not evaluated theQuerySet, since Django will perform aSELECT COUNT(*)behind the scenes, and you avoid loading all the data into memory.As an aside – why are you directing them to
/home/if the e-mail address isn’t matched, and to/home/login/if their credentials fail? I would have thought it makes more sense to redirect them to the same place for those two cases.