Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user\'s email address instead of them creating a userna
The easiest way is to lookup the username based on the email in the login view. That way you can leave everything else alone:
from django.contrib.auth import authenticate, login as auth_login
def _is_valid_email(email):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email(email)
return True
except ValidationError:
return False
def login(request):
next = request.GET.get('next', '/')
if request.method == 'POST':
username = request.POST['username'].lower() # case insensitivity
password = request.POST['password']
if _is_valid_email(username):
try:
username = User.objects.filter(email=username).values_list('username', flat=True)
except User.DoesNotExist:
username = None
kwargs = {'username': username, 'password': password}
user = authenticate(**kwargs)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect(next or '/')
else:
messages.info(request, "Error User account has not been activated..")
else:
messages.info(request, "Error Username or password was incorrect.")
return render_to_response('accounts/login.html', {}, context_instance=RequestContext(request))
In your template set the next variable accordingly, i.e.
And give your username / password inputs the right names, i.e. username, password.
UPDATE:
Alternatively, the if _is_valid_email(email): call can be replaced with if '@' in username. That way you can drop the _is_valid_email function. This really depends on how you define your username. It will not work if you allow the '@' character in your usernames.