Home > other >  lower() was called on None
lower() was called on None

Time:11-17

I have created a custom function to create custom username in a class Inheriting DefaultSocialAccountAdapter. The code is as follows.

def _build_username(self,data):

        from allauth.utils import generate_unique_username

        if(not data.get('username')):

            first_name=data.get('first_name','').lower()

            last_name=data.get('last_name','').lower()

            suggested_username = (f"{first_name}{last_name}",)

            username = generate_unique_username(suggested_username)

            return username

        

But it throws lower() was called on None

I was trying to convert the name to lowercase because that is how our database supports usernames. This happens when i try to perform google login authentication method.

CodePudding user response:

Its because, the data may contain first_name or last_name key but its value may be None. So you can add a condition check to ensure its not None

def _build_username(self,data):
    from allauth.utils import generate_unique_username
    if(not data.get('username')):
        first_name=data.get('first_name','')
        last_name=data.get('last_name','')
        l=[]
        if(first_name):
            l.append(first_name.lower().strip())
        else:
            l.append('')
        if(last_name):
            l.append(last_name.lower().strip())
        else:
            l.append('')
        suggested_username = (f"{l[0]}{l[1]}",)
        username = generate_unique_username(suggested_username)
        return username

CodePudding user response:

This is possible if the 'first_name' is in data and associates the key with None, so {'first_name': None} for example.

You can use the or operator to replace this with the empty string, so:

def _build_username(self,data):
    from allauth.utils import generate_unique_username
    username = data.get('username')
    if not username:
        first_name=data.get('first_name') or ''
        last_name=data.get('last_name') or ''
        username = generate_unique_username(f'{first_name}{last_name}'.lower())
    return username
  • Related