Mermoz
Mermoz

Reputation: 15474

Django: making a clean username with first_name.last_name

instead of a fancy username, it would be better for my website to have a normalized username in the form first_name.last_name.

It is simple to create the new user with this kind of username

username = cleaned_data.get('first_name') + "." + cleaned_data.get('name')

but what is the best way to clean both fields in order that they contain:

  1. no spaces ex: Théodore de Banville
  2. no accents ex: Raphaël LeBlond
  3. any other problematic characters

I thought of using re and unidecode:

username = re.sub(r"\s+", "", username).lowercase
username = unidecode(username)

but is this enought?

EDIT: here is my current solution:

            fname = unicode(self.cleaned_data['first_name'])
            fname = unidecode(fname)
            fname = slugify(fname)
            name = unicode(self.cleaned_data['last_name'])
            name = unidecode(name)
            name = slugify(name)
            username = fname + "." + name

Upvotes: 2

Views: 1510

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

That's mostly what slugify() does, but the use of unidecode() is a huge improvement. The only change I'd make is to apply unidecode() first, then remove the spaces.

Upvotes: 1

Related Questions