Pages

0 comments

Django login with email or username

My new django project requires users to log in using their username or email. I googled and searched SO for a solution. But most of them were for authentication using email or creating a new backend. I wanted to allow my users to log in using email or username and I am too lazy to write a new authentication backend.  So I extended default django authentication form . And with the help of this snippet I came up with this solution. And obviously emails for users are made unique.

forms.py
from django.utils.translation import ugettext, ugettext_lazy as _
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate
        
class MyAuthenticationForm(AuthenticationForm):
    username = forms.CharField(label=_("Username"), max_length=100)
    #max length changed from 30 to 100
    def clean(self):
        username = self.cleaned_data.get('username').lower()
        password = self.cleaned_data.get('password')

        if username and password:
            #modifying clean method
            #next 5 lines are added
            if '@' in username:#checking if email
                try:
                    #getting username from the User object for that email
                    username = User.objects.get(email=username).username
                except:
                    User.DoesNotExist
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'])
            elif not self.user_cache.is_active:
                raise forms.ValidationError(self.error_messages['inactive'])
        self.check_for_test_cookie()
        return self.cleaned_data
urls.py
url(r'^login/$', 'django.contrib.auth.views.login',
            {'authentication_form':MyAuthenticationForm }),

Happy coding.:)

0 comments

Google Easter Eggs

Google's latest Easter egg 'Let it snow' made me to search for the past Google Easter eggs and here is some of my findings

Do a barell roll : which rotates the page 360°.

Tilt : which makes the page a little tilted.

Ascii art : which shows the ascii art of Google logo.

Christmas lights : brings X'mas lights.

Hanukkah : shows stars of David.

The loneliest number : discovers the loner

Google for Hackers.

Google for Pirates.

and here is some i'm feeling lucky fun. Type these words in Google and click i'm feeling lucky.

"Google Gravity"

"Google Sphere"

"who is the cutest"

"find chuck norris"

I know there is still a lot out there but i am just winding up now :)