Search code examples
pythondjangodjango-rest-frameworkrestful-url

how to ignore forward slash from django URL in a parameter


I am using django version 2.2.5. Below is my urls.py

from django.urls import path, include
from . import views

urlpatterns = [
   path('manifest/', views.home),
   path('manifest/<str:some_id>/', views.manifest),
]

It works fine when some_id does not contain any forward slash(/). E.g. http://127.0.0.1:8000/manifest/name:19.2.4:develop:1/

In the following manifest function from views.py, I am able to get the some_id

def manifest(request, some_id):
     print(some_id)

##prints below:
##[21/Oct/2019 19:36:55] "GET /manifest/name:19.2.4:develop:1 HTTP/1.1" 301 0
##name:19.2.4:develop:1

However, when the some_id contains forward slash in it, I don't get the whole id. E.g., from the above URL if I would replace "develop" with "release/19.2.4" http://127.0.0.1:8000/manifest/name:19.2.4:release/19.2.4:1/

"GET /manifest/name:19.2.4:release/19.2.4:1/ HTTP/1.1" 404 3080

This is because of the forward slash being used as delimiter. Is there any way to ignore this forward slash inside of the some_id parameter? The expectation is to get name:19.2.4:release/19.2.4:1 as some_id in the views.py

Note: The format of a valid some_id is it has 4 parts delimited by ":". e.g.: name:version:branch:num, where only the branch section could have one or more slash(/) in it.


Solution

  • You might want to use good ol' re_path In your case, that'll give

    from django.urls import path, re_path, include
    from . import views
    
    urlpatterns = [
       path('manifest/', views.home),
       re_path(r'manifest/(?P<some_id>\w+)/', views.manifest),
    ]
    

    Your URL is structured though, have you tried something like:

    path('manifest/<str:name>:<str:version>:<path:branch>:<str:num>/', views.manifest),