Son Tran
Son Tran

Reputation: 1536

Optional some special characters such as @, - or . in Django URL

I want to create a url that allow both user email and username in Django such as:

http://mysite.dev/profile/[email protected]

or

http://mysite.dev/profile/this-is-my-username

Both above must be allowed. How can I do it?

Upvotes: 1

Views: 1866

Answers (1)

Lancelot HARDEL
Lancelot HARDEL

Reputation: 411

You can use regex to match an url.
Here's a regex matching your two cases : [\w\d@\.-]+.

from django.conf.urls import url
from youapp import views

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

Take a look at the Django documentation : https://docs.djangoproject.com/en/1.8/topics/http/urls/#how-django-processes-a-request

Upvotes: 2

Related Questions