469👍
Updated 2023
This answer is outdated but still gets activity.
See @j-i-l‘s answer below for Django > 2 and reference to current docs.
Original 2013 Answer
There are several approaches.
One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional
Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.
urlpatterns = patterns('',
url(r'^project_config/$', views.foo),
url(r'^project_config/(?P<product>\w+)/$', views.foo),
url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)
Keep in mind that in your view you’ll also need to set a default for the optional URL parameter, or you’ll get an error:
def foo(request, optional_parameter=''):
# Your code goes here
66👍
Django > 2.0 version:
The approach is essentially identical with the one given in Yuji ‘Tomita’ Tomita’s Answer. Affected, however, is the syntax:
# URLconf
...
urlpatterns = [
path(
'project_config/<product>/',
views.get_product,
name='project_config'
),
path(
'project_config/<product>/<project_id>/',
views.get_product,
name='project_config'
),
]
# View (in views.py)
def get_product(request, product, project_id='None'):
# Output the appropriate product
...
Using path()
you can also pass extra arguments to a view with the optional argument kwargs
that is of type dict
. In this case your view would not need a default for the attribute project_id
:
...
path(
'project_config/<product>/',
views.get_product,
kwargs={'project_id': None},
name='project_config'
),
...
For how this is done in the most recent Django version, see the official docs about URL dispatching.
- [Django]-Passing STATIC_URL to file javascript with django
- [Django]-Creating email templates with Django
- [Django]-How to combine django "prefetch_related" and "values" methods?
37👍
You can use nested routes
Django <1.8
urlpatterns = patterns(''
url(r'^project_config/', include(patterns('',
url(r'^$', ProjectConfigView.as_view(), name="project_config")
url(r'^(?P<product>\w+)$', include(patterns('',
url(r'^$', ProductView.as_view(), name="product"),
url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
))),
))),
)
Django >=1.8
urlpatterns = [
url(r'^project_config/', include([
url(r'^$', ProjectConfigView.as_view(), name="project_config")
url(r'^(?P<product>\w+)$', include([
url(r'^$', ProductView.as_view(), name="product"),
url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
])),
])),
]
This is a lot more DRY (Say you wanted to rename the product
kwarg to product_id
, you only have to change line 4, and it will affect the below URLs.
Edited for Django 1.8 and above
- [Django]-Django QuerySet order
- [Django]-Django Form File Field disappears on form error
- [Django]-Django south migration – Adding FULLTEXT indexes
34👍
Even simpler is to use:
(?P<project_id>\w+|)
The “(a|b)” means a or b, so in your case it would be one or more word characters (\w+) or nothing.
So it would look like:
url(
r'^project_config/(?P<product>\w+)/(?P<project_id>\w+|)/$',
'tool.views.ProjectConfig',
name='project_config'
),
- [Django]-Is there a way to loop over two lists simultaneously in django?
- [Django]-Django TextField and CharField is stripping spaces and blank lines
- [Django]-Django QuerySet order
9👍
Thought I’d add a bit to the answer.
If you have multiple URL definitions then you’ll have to name each of them separately. So you lose the flexibility when calling reverse since one reverse will expect a parameter while the other won’t.
Another way to use regex to accommodate the optional parameter:
r'^project_config/(?P<product>\w+)/((?P<project_id>\w+)/)?$'
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-How to tell if a task has already been queued in django-celery?
- [Django]-How can I handle Exceptions raised by dango-social-auth?
5👍
Django = 2.2
urlpatterns = [
re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-Django models avoid duplicates
2👍
Use ? work well, you can check on pythex. Remember to add the parameters *args and **kwargs in the definition of the view methods
url('project_config/(?P<product>\w+)?(/(?P<project_id>\w+/)?)?', tool.views.ProjectConfig, name='project_config')
- [Django]-How to concatenate strings in django templates?
- [Django]-How can I create a deep clone of a DB object in Django?
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?