Slugify String in Django

I developed a form in which the user adds his first name and last name .

For the username (a unique ) property, I developed 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 is 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 cannot figure out what to do before Step 3 for implementation. Where should I put [:len(u_username)] to compare strings?

EDIT:

This method is used if there are multiple instances of Harry-Potter , resolving the problem of adding an integer at the end. My question is: how to check how the last integer was added with Harry-Potter .

+6
source share
1 answer

Try the following:

 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 # ie '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) 
+9
source

Source: https://habr.com/ru/post/945608/


All Articles