Slugify string in Django

xan picture xan · May 22, 2013 · Viewed 9.3k times · Source

I have developed a form, where the user adds his/her first name and last name.

For the username (a unique property), I've devised the following method:

FirstName: harrY LastName: PottEr --> username: Harry-Potter

FirstName: HARRY LastName: POTTER --> username: Harry-Potter-1

FirstName: harrY LastName: PottEr --> username: Harry-Potter-2

And so on..

Here's my function definition:

def return_slug(firstname, lastname):
    u_username = firstname.title()+'-'+lastname.title()         //Step 1
    u_username = '-'.join(u_username.split())                     //Step 2
    count = User.objects.filter(username=u_username).count()    //Step 3
    if count==0:
        return (u_username)
    else:
        return (u_username+'-%s' % count)

I can't figure out what to do before Step 3 for the implementation. Where should I put [:len(u_username)] to compare the strings?

EDIT:

This method is applied if there are multiple instances of Harry-Potter, by resolving the issue of adding an integer in the end. My question is: How will I check that how what was the last integer appended to Harry-Potter.

Answer

Michael Waterfall picture Michael Waterfall · May 22, 2013

Try this:

from django.utils.text import slugify

def return_slug(firstname, lastname):

    # get a slug of the firstname and last name.
    # it will normalize the string and add dashes for spaces
    # i.e. 'HaRrY POTTer' -> 'harry-potter'
    u_username = slugify(unicode('%s %s' % (firstname, lastname)))

    # split the username by the dashes, capitalize each part and re-combine
    # 'harry-potter' -> 'Harry-Potter'
    u_username = '-'.join([x.capitalize() for x in u_username.split('-')])

    # count the number of users that start with the username
    count = User.objects.filter(username__startswith=u_username).count()
    if count == 0:
        return u_username
    else:
        return '%s-%d' % (u_username, count)