0

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')
B. Victor
  • 94
  • 1
  • 8

2 Answers2

1

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 :)

roo1989
  • 86
  • 4
  • I understand your point but I really need a custom URL path that would be delimited by /. But anyways your point is quite valid overall. – B. Victor Sep 30 '20 at 15:33
1

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'),
]
Marvin Correia
  • 851
  • 7
  • 10
  • I really have no clue how to use regex. I will look at tutorials about that. I'm just having one question: Will re_path help me achieve what I asked for? – B. Victor Sep 30 '20 at 15:38
  • @B.Victor Check the edited answer I add the code that you need – Marvin Correia Sep 30 '20 at 15:44
  • It actually will give you only one parameter 'path' but from this parameter I can split the string as I want and then manipulate it as I want. Thanks – B. Victor Sep 30 '20 at 15:54
  • 1
    Another option is to use `path('test/', views.test, name='test')`. The `path:` converter means it matches slashes. – Alasdair Sep 30 '20 at 16:35
  • Note that `url()` was deprecated in Django 3.1, so it's not recommended to use it in new code. – Alasdair Sep 30 '20 at 16:35