0

Would anyone please explain to me how to passing parameter in Django URL

I created view in view.py "def hours_ahead(request, offset)" to calculate the time ahead. Then on URL.py I call it with re_path(r'^time/plus/\d{1,2}/$', hours_ahead).

But I get the error message when I put the url http://127.0.0.1:8000/time/plus/2/

TypeError at /time/plus/2/ hours_ahead() missing 1 required positional argument: 'offset'

1
  • please, give more details about your implementation Commented Sep 18, 2020 at 8:49

2 Answers 2

0

offset should be the data capture in the URL (identified within brackets in your URL pattern):

(r'^time/plus/(\d{1,2})/$', hours_ahead)
Sign up to request clarification or add additional context in comments.

Comments

0

You configured the regular expression in your URL but didn't specify the parameter name that will be sent to your view function.

The following URL definition should work. Notice that the ?P part that is used to define the parameter that will capture the value matching the regular expression.

re_path(r'^time/plus/(?P<offset>\d{1,2})/$', hours_ahead)

Note 1: that if you're not really strict on the amount of hours that can be added, you can use simpler URL definition that just specifies an integer:

path('time/plus/<int:offset>/$', hours_ahead)

But that will allow a caller of your URL to add a huge amount of hours, as long as it fits the integer.

Note 2: Not really your question but if you think about correct API / interface design this can be important: what you're doing is an action, adding hours. That action is now triggered by an HTTP GET request. Actions should always be triggered by other HTTP methods such as POST, PATCH, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.