[Fixed]-How to use email instead of username for user authentication?

7πŸ‘

I found this snippet when reading a duplicate question to this one. Also check this code:

class UserForm( forms.ModelForm ):
    class Meta:
        model= User
        exclude= ('email',)
    username = forms.EmailField(max_length=64,
        help_text = "The person's email address.")
    def clean_email( self ):
        email= self.cleaned_data['username']
        return email

class UserAdmin( admin.ModelAdmin ):
    form= UserForm
    list_display = ( 'email', 'first_name', 'last_name', 'is_staff' )
    list_filter = ( 'is_staff', )
    search_fields = ( 'email', )

admin.site.unregister( User )
admin.site.register( User, UserAdmin )

Neither answer is originally mine. Up vote on the other thread to the owners for the karma boost. I just copied them here to make this thread as complete as possible.

5πŸ‘

Check out this snippet, and read the comments for updates.

For the form, why not just inherit from (or directly use) the auth login form. See django/contrib/auth/forms.py

πŸ‘€Van Gale

3πŸ‘

Please see the below link which illustrates the way in which we should solve the problem.

http://groups.google.com/group/django-users/browse_thread/thread/c943ede66e6807c

1πŸ‘

Sounds like you can just mask the username with the word β€œemail” and all the usernames will just have the email show up instead.

πŸ‘€jerebear

-1πŸ‘

Unless I missed something, the solution should be really simple; just make a normal form with a text field and a password field. When the HTTP request method is POST, try to fetch the user with the given e-mail address. If such a user doesn’t exist, you have an error. If the user does exist, try to authenticate the user and log her in.

πŸ‘€Deniz Dogan

Leave a comment