1

How do I capture multiple values from a URL in Django?

Conditions: I would like to capture ids from a URL. The ids vary in length (consist of numbers only), and there can be multiple ids in the URL. Check out the following two examples:

http://127.0.0.1:8000/library/check?id=53&id=1234

http://127.0.0.1:8000/library/check?id=4654789&id=54777&id=44

The solution may include regex.

urlpatterns = [
    path("", view=my_view),
    path("<solution_comes_here>", view=check_view, name="check_view"),
]

P.S. all solutions I found on this platform and Django documentation only explain cases for capturing single values from the URL

1
  • path('check'). The querystring is not part of the path. This can be determined with request.GET. Commented Aug 25, 2022 at 8:43

2 Answers 2

2

request.GET is a Querydict. It has more methods than an ordinary dict.

What you want for this is request.GET.getlist("id") which will return a list of id values. .get("id") will return only the last of them.

Sign up to request clarification or add additional context in comments.

Comments

1

You use:

urlpatterns = [
    path('', view=my_view),
    path('check/', view=check_view, name='check_view'),
]

Indeed, the querystring is not part of the path. This can be determined with request.GET. So you can obtain the ids with:

def check_view(request):
    ids = request.GET.getlist('id')  # ['3654789', '54777', '44']
    # …

There is however no guarantee that the ids will only be numerical, so you will need to validate that in the view itself.

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.