Opened 4 years ago

Closed 4 years ago

#31809 closed Uncategorized (invalid)

Regex URL patterns with conditional capture break default values in view functions

Reported by: Zoltán Adamek Owned by: nobody
Component: Core (URLs) Version: 3.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello,

When I use a conditional, named capture group in a URL pattern with a view function which has a default value, the default value is not adhered to. For a full example, this minimal Django app below will act like the following:

  • On visiting /this, it will print "this" (as expected).
  • On visiting /that, it will print "that" (as expected).
  • On visiting / (=not specifying anything), instead of falling back to the default view parameter "this", I get None.
import sys

from django.conf import settings
from django.conf.urls import url 
from django.core.management import execute_from_command_line
from django.http import HttpResponse

settings.configure(
    DEBUG=True,
    ROOT_URLCONF=__name__,
)


def routing_example(request, choices="this"):
    return HttpResponse('<html><body>{text}</body></html>'.format(text=choice))

urlpatterns = [
    url(r'^(?:(?P<choice>(this|that)))?$', routing_example),
]

if __name__ == '__main__':
    execute_from_command_line(sys.argv)

Change History (1)

comment:1 by Mariusz Felisiak, 4 years ago

Component: UncategorizedCore (URLs)
Resolution: invalid
Status: newclosed

This is an expected behavior because choice is an optional in your pattern, if you want to specify default parameter for you views you should use two patterns:

urlpatterns = [
    url(r'^$', routing_example),
    url(r'^(?:(?P<choice>(this|that)))?$', routing_example),
]

See Specifying defaults for view arguments. Trac is not a support channel so if you have more question please TicketClosingReasons/UseSupportChannels.

Note: See TracTickets for help on using tickets.
Back to Top