Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: urlpattern for username?

Up to now a team mate used this code for the url patterns of user names:

# urls.py
urlpatterns = patterns('...',
   url(r'^user/(?P<username>[.-_\w]+)/foo', 'myapp.views.foo'),
   ....

there is a hidden bug: If the username contains a - the reversing would fail, since the beginning of the regex pattern [.-_ means "all chars from . to _".

What pattern can be used to match all valid usernames?

PS: I guess adding the - sign to the regex is not enough, if you want to match all possible user names in django.

like image 851
guettli Avatar asked Sep 04 '15 09:09

guettli


3 Answers

Based on what I see in the AbstractUser model, I think a better regex to use to grab the username is (?P<username>[\w.@+-]+).

like image 158
Navneet Avatar answered Oct 22 '22 05:10

Navneet


I don't think you should put any username validation in your URL pattern. Keep your validation in one place -- the place you create your accounts for the first time.

You should match anything the user supplies there, and pass that to a safe database function to look up the username and fail if it doesn't exist.

So, in your url pattern, let the browser send anything that is nonempty, and rely on your very smart database to tell you what you previously decided was valid or not.

url(r'^user/(?P<username>.+)/foo$', 'myapp.views.foo'),

Also, note the "$" on the end.

like image 7
Chad Miller Avatar answered Oct 22 '22 03:10

Chad Miller


You can either move the hyphen to the start of the character class,

[-.\w]

or you can escape it with a backslash

[.\-\w]

Note I have removed the underscore, since it is included in \w. I am also assuming that you only want to accept ., - and \w, and you don't want to accept all the characters from . to _. That range includes characters like @, so you might want to check that all your usernames match the new regex.

like image 4
Alasdair Avatar answered Oct 22 '22 05:10

Alasdair