1
app_name = 'app_name'
path('url/<uuid:uuid>',someview.as_view(),name='somename')

def get_url():
   return reverse('app_name:somename',args=None)

I want get_url to return 'url/' Is it possible?

If not, can i somehow get the partial url without the param like 'url/'?

Ahsan
  • 31
  • 1
  • 6
  • No, you can't. The idea is that you should fill in the parameters. It would also be an invalid URL. The slashes in the path are not really "compartments" in the sense that people interpret these as compartments, but it is just a simple slash. – Willem Van Onsem Aug 24 '20 at 01:13
  • Both forward and reverse lookup of the URL `url/` would require an additional route. It could lead to the same view if a [default value](https://docs.djangoproject.com/en/3.1/topics/http/urls/#specifying-defaults-for-view-arguments) is defined. – Klaus D. Aug 24 '20 at 01:17

2 Answers2

2

You can have multiple paths with the same name but with different parameters.

app_name = 'app_name'

urlpatterns = [
    path('url/', someview.as_view(), name='somename'),
    path('url/<str:foo>/', someview.as_view(), name='somename'),
]

When you use reverse the url pattern that matches the name and parameters that you pass will be returned

reverse('app_name:somename', kwargs={'foo': 'bar'})  # /url/bar/
reverse('app_name:somename')  # /url/
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
0

You could use re_path:

from django.urls import re_path

urlpatterns = [
   re_path('url/(?P<some_id>[0-9]*)$', some_view, name='someview-name'),
]

This way, url/ is valid, url/12 is valid, but url/foobar is not.

Note that when you return reverse('app_name:somename',args=None), None is interpreted as a string, so it's better to do return reverse('app_name:somename',args=''). Anyway, re_path('url/(?P<some_id>[0-9]*|None)$' also works.

Guillaume Lebreton
  • 2,586
  • 16
  • 25