'Django URL regex to include forward slashes
I am having trouble with creating a Django URL regex which allows all characters (including forward slashes). More specifically, the problem I am having is differentiating between forward slashes used in the URL args and forward slashes used as delimiters in the URL.
example:
I have a URL which looks like this: localhost:8000/jfe/customer/customerNumb/invoice2/portfolio/
this consists of 3 URL arguments: customerNumb, invoice2, portfolio.
My goal is to make it so argument 2 can contain special characters including '/' so the 2nd argument could be something like "KJ 02/2017" (without quotes).
example: localhost:8000/jfe/customer/customerNumb/KJ 02/2017/portfolio/
in the example of using "KJ 02/2017" I am having trouble with differentiating the '/' in "KJ 02/2017" and the '/' which separates arg2 and arg3.
my regex:
url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>[^/]+)/$')
url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>[^/]+)/(?P<portfolio>[^/]+)/$')
I have also tried
url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>.+)/$')
url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>.+)/(?P<portfolio>[^/]+)/$')
If I encode the URL:
example: localhost:8000/jfe/customer/customerNumb/KJ%2002%2F2017/portfolio/ the regex will parse it like this:
arg1: customerNumb, arg2: KJ%2002%2F2017/portfolio/
when I want:
arg1: customerNumb arg2: KJ%2002%2F2017 arg3: portfolio
can someone please help me understand where I am messing up in my regex? or let me know if its even possible to have '/' included in url arguments?
thank you
EDIT: it was pointed out that my 2nd attempt works, which is true, but I would like to mention the Django seems to decode the URL before passing it the regex. As a result the regex sees it as this:
localhost:8000/jfe/customer/customerNumb/KJ 02/2017/portfolio/
Solution 1:[1]
This should work:
"/[0-9]+(?:-|.|\/)+[a-zA-Z]+(?:-|.|\/)+[0-9]/"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cigien |
