Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-Registration: Email as username

How do I use emails instead of username for authentication using django-registration.

Further how do I enforce this change once I have already installed the registration module.

Do I edit the solution here Anyone knows a good hack to make django-registration use emails as usernames? in the lib folder?

like image 829
Eva611 Avatar asked Jun 15 '11 21:06

Eva611


People also ask

How do I make my email address unique in Django?

You have to declare the email field in your AbstractBaseUser model as unique=True . @mogoli Remove your db and migrations. In settings.py, add AUTH_USER_MODEL='new_user_model. MyUser'.

How do I log into my Django email?

Email authentication for Django 3.x For using email/username and password for authentication instead of the default username and password authentication, we need to override two methods of ModelBackend class: authenticate() and get_user():


2 Answers

Dear fellow Django Coder,

I think this is the best way to do it. Good luck!

First step, is to create the form you'd like to use.

project/accounts/forms.py

from django import forms from registration.forms import RegistrationForm from django.contrib.auth.models import User  class Email(forms.EmailField):      def clean(self, value):         super(Email, self).clean(value)         try:             User.objects.get(email=value)             raise forms.ValidationError("This email is already registered. Use the 'forgot password' link on the login page")         except User.DoesNotExist:             return value   class UserRegistrationForm(forms.Form):     password1 = forms.CharField(widget=forms.PasswordInput(), label="Password")     password2 = forms.CharField(widget=forms.PasswordInput(), label="Repeat your password")     #email will be become username     email = Email()      def clean_password(self):         if self.data['password1'] != self.data['password2']:             raise forms.ValidationError('Passwords are not the same')         return self.data['password1'] 

Here you are creating a file to override the register() function in django-registration.

project/accounts/regbackend.py

from django.conf import settings from django.contrib.sites.models import RequestSite from django.contrib.sites.models import Site  from registration import signals from registration.forms import RegistrationForm from registration.models import RegistrationProfile  from registration.backends import default   class Backend(default.DefaultBackend):     def register(self, request, **kwargs):         email, password = kwargs['email'], kwargs['password1']         username = email         if Site._meta.installed:             site = Site.objects.get_current()         else:             site = RequestSite(request)         new_user = RegistrationProfile.objects.create_inactive_user(username, email,                                                                     password, site)         signals.user_registered.send(sender=self.__class__,                                      user=new_user,                                      request=request)         return new_user 

Direct your urls to paths you want to use.

project/urls.py

(r'^accounts/', include('registration.backends.default.urls')), 

Tell your urls to use the custom backend for the registration view. Also, import the form you created and add it to the url to be processed by the view.

project/accounts/urls.py

from django.conf.urls.defaults import * from registration.backends.default.urls import * from accounts.forms import UserRegistrationForm  urlpatterns += patterns('',      #customize user registration form     url(r'^register/$', 'registration.views.register',         {             'backend': 'accounts.regbackend.Backend',             'form_class' : UserRegistrationForm         },         name='registration_register'     ),  )  

Hope that works!

-Matt

like image 82
Matt Avatar answered Nov 04 '22 23:11

Matt


For Django >= 1.3 and < 1.5 there's Django email as username on github.

Recently I'm using registration and I switch easily to django-registration-email. It works fine on Django 1.4, reusing the same templates and simply adding REGISTRATION_EMAIL_ACTIVATE_SUCCESS_URL = "/profiles/create/" to redirect to the profile creation page.

Django 1.5 overcome this issue through custom User model where you can specify what field is used as username. As stated in Django 1.5 documentation:

A string describing the name of the field on the User model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier.

like image 32
chirale Avatar answered Nov 04 '22 23:11

chirale