supermario
supermario

Reputation: 2755

How to allow "@" in django urls?

I'd like user to be able to choose at sign @ as well as alphanumeric and hyphen in their username. However this leads to 404 in the relevant regexp:

url(r'^(?P<username>[\w.-]+)/$', 'userprofile.views.profile'),

I tried [\w.-@] and [\w.-\@] but none worked.

How to fix this?

Upvotes: 0

Views: 189

Answers (2)

user764357
user764357

Reputation:

The question states nothing about email addresses, just wanting @ symbols in usernames, and this should suffice:

url(r'^(?P<username>[\w@\d-]+)/$', 'userprofile.views.profile'),

The relevant bit is: [\w@\d-\.]+, which matches at least one of any word character, an @ symbol*, any digit, a hyphen or a dot.

* The @ symbol is the only character on a standard 101 keyboard to not have a name!

Upvotes: 2

Brandon Taylor
Brandon Taylor

Reputation: 34573

You can just make the @ optional. This pattern will catch most email-like strings.

(?P<username>[-\w]+(?:\@)?[A-Za-z0-9.-]+(?:\.)?[A-Za-z]{2,4})

If you want to catch something like a@a you will need to make everything after, and including the period optional:

(?P<username>[-\w]+(?:\@)?[A-Za-z0-9.-]+(?:\.[A-Za-z]{2,4})?)?

That pattern will match:

[email protected]
foo@bar
foobar

Upvotes: 1

Related Questions