Django url passing as many parameters as you want delimited by /

628 views Asked by At

How can I define the URL pattern so that I can pass to an URL as many parameters as I want? I really researched the documentation and other stackoverflow questions but I didn't found something similar to that. I need this to work as a filter for an ecommerce website.

I would like to achieve something like this:

urlpatterns = [
    path('test/<str:var1>-<str:var2>/<str:var3>-<str:var4>/...', views.test, name='test'),
]

And in my view function I would define it like that:

def test(request, *args, **kwargs):
    # Do whatever you want with kwargs
    return HttpResponse('Test')
2

There are 2 answers

5
Marvin Correia On BEST ANSWER

I think this is a wrong way to make a path, if you want to use it as a filter instead of using it in the path you should use url parameters as a get request.

But if you insist on doing that you can use the Regular expressions 're_path'

# urls.py

from django.urls import path, re_path
from django.conf.urls import url
from myapp import views

urlpatterns = [
    re_path(r'^test/(?P<path>.*)$', views.test, name='test'),
    # or use url instead it's same thing
    url(r'^test/(?P<path>.*)$', views.test, name='test'),
]
1
roo1989 On

Have you considered using query_params?

That is path('test', views.test, name='test')

URL: /test/?filter=asd....

Then access it via the request in the view:

def test(request):
    params = request.GET.get('filter', None)
    return HttpResponse()

See if you can work out your problem like that :)