semekh
semekh

Reputation: 3917

Recursive URL routing in Django

I want to have a (fairly simple) emulation of SELECT queries through URLs.

For example, in a blogging engine, You'd like /tag/sometag/ to refer to the posts having the sometag tag. Also /tag/sometag/or/tag/other/and/year/2013 should be a valid URL, beside other more complex urls. So, having (theoretically) no limit on the size of the url, I would suggest this should be done recursively, but how could it be handled in Django URL Routing model?

Upvotes: 3

Views: 927

Answers (3)

AcaNg
AcaNg

Reputation: 706

I know this is an old question but for those who reach here in future, starting from django 2.0+, you can use path converter with path to match the path in the url:

# urls.py
urlpatterns = [
    path('query/<path:p>/', views.query, name='query'),
]
# views.py
def query(request, p):
    # here, p = "tag/sometag/or/tag/other/and/year/2013"
    ...

Upvotes: 0

Weilory
Weilory

Reputation: 3121

update 2021

django.conf.urls.url is deprecated in version 3.1 and above. Here is the solution for recursive url routing in django:

urls.py

from django.urls import path, re_path
from .views import index


urlpatterns = [
    re_path(r'^query/([\w/]*)/$', index, name='index'),
]

views.py

from django.shortcuts import render, HttpResponse


# Create your views here.
def index(request, *args, **kwargs):
    print('-----')
    print(args)
    print(kwargs)
    return HttpResponse('<h1>hello world</h1>')

If I call python manage.py run server, and go to 'http://127.0.0.1:8000/query/nice/', I can see these in terminal:

-----
('nice',)
{}

Upvotes: 1

jordiburgos
jordiburgos

Reputation: 6302

I would use a common URL pattern for all those URLs.

url(r'^query/([\w/]*)/$', 'app.views.view_with_query'),

You would receive all the "tag/sometag/or/tag/other/and/year/2013" as a param for the view.

Then, you can parse the param and extract the info (tag, value, tag, value, year, value) to make the query.

Upvotes: 4

Related Questions