Hillary Sanders Hillary Sanders - 27 days ago 10
Python Question

django username-related URL resolution fails when username has odd characters

So, the default Django

User
model allows usernames to have a few weird characters - e.g. I can make a user called '@.+-_'. However, I've made a user profile page whose url is dependent on username. I'd like to use the username instead of user_id because it's more readable:

url(r'^public_profile/(?P<username>[\w\d]+)$',
views.public_profile,
name='public_profile'),


This works fine for most users, but when a user with a funky name - e.g. '@.+-_' is looked up, the public_profile page fails with a

Reverse for 'public_profile' with arguments '('@.+-_',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['public_profile/(?P<username>[\\w\\d]+)$']


error. --> So, I figured I could add a 'slug' field to the
User
model, and use that plus the user_id in the url (so slugs don't accidentally collide), but I'm not sure how to modify the
User
model since it's part of django. Any ideas on how to do this?

Thanks

Answer

Rather than altering the model, you should alter the URL so that it doesn't fail. The problem is your regex: \w\d matches alphanumeric characters only (in fact \w does that already, the \d is superfluous). You could add the specific characters you want to match:

r'^public_profile/(?P<username>[+-@_.\w]+)$'

or just match everything:

r'^public_profile/(?P<username>.+)$'
Comments