Hillary Sanders Hillary Sanders - 1 year ago 82
Python Question

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

So, the default Django

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:


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
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
model since it's part of django. Any ideas on how to do this?


Answer Source

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:


or just match everything:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download