Opened 8 months ago

Closed 8 months ago

#35403 closed Uncategorized (invalid)

URL path with optional parameter

Reported by: Patrick Hintermayer Owned by: nobody
Component: Uncategorized Version: 5.0
Severity: Normal Keywords: url
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I sometimes have a class based view which has a GET and a POST method, for example a ListView which shows some objects with a POST form to create something out of it.

In the documentation (https://docs.djangoproject.com/en/5.0/topics/http/urls/) I did not find a simple way of doing that. Asking GitHub Copilot suggested me adding a question mark at the end to mark a parameter as optional which does not work.

I found myself 2 solutions:

  1. using regex which looks cumbersome just for marking something as optional:

    Code highlighting:

    re_path(
          r"^activate/(?P<activation_token>[^/]+)?$",
          views.UserActivationView.as_view(),
          name="user_activation",
      )
    


  1. using 2 paths: one without a parameter and one with a parameter:

    Code highlighting:

    path(
          "activate/",
          views.UserActivationView.as_view(),
          name="user_activation",
      ),
      path(
          "activate/<str:activation_token>/",
          views.UserActivationView.as_view(),
          name="user_activation",
      )
    


For this ticket, I want to suggest a) improve the documentation with a simple example how to do that and/or b) can this be simplified in django by adding for example a question mark at the end like "/<int:some_id?>/" or "/<int?:some_id>/":

Code highlighting:

path(
      "activate/<str:activation_token?>/",
      views.UserActivationView.as_view(),
      name="user_activation",
  )

Change History (1)

comment:1 by Sarah Boyce, 8 months ago

Resolution: invalid
Status: newclosed

Hi Patrick 👋 I think this ticket is a bit of a mix of a support request, new feature request, and docs update request.

With support requests (how do I best achieve X with Django), I recommend asking in the forum because you will have many more people who can help answer.

I think I would have either gone for solution 2 using a default for activation_token (a bit like what is documented here) or used a query string like activate/?token=some-activation-token and then I can access token in the QueryDict (example involving pagination).
I believe we have this functionality already and so something like "/<int:some_id?>/" would not be required.

Before we can discuss a docs update, you need to know what you would have wanted to see. So I would encourage that you discuss this topic on the forum, agree on an approach, and then decide if the docs are clear enough or if there is an enhancement available.

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