I have urls.py in my project.
I want to create URL like localhost:8000/v1/user?id=1
Can anyone help me how I can create the above URL.
Thanks
- 73
- 2
- 12
-
Do you want to add specifically `id=1`, or can id be any number? – John Gordon Nov 02 '22 at 17:44
-
Can be any integer number – Prafulla Nov 02 '22 at 17:44
-
1Does this answer your question? [Django and query string parameters](https://stackoverflow.com/questions/3711349/django-and-query-string-parameters) – Henry Woody Nov 02 '22 at 17:47
1 Answers
The part right from the question mark (?) is the query string [wiki]. The urls.py do not inspect the querystring, they only care about the path (the part left from the question mark).
The urls.py thus uses:
urlpatterns = [path('/v1/user', some_view)]
in the view you then can access the last value that associates with the id key with request.GET['id']. Here request.GET is a QueryDict [Django-doc]: it is a dictionary-like object but a key can be associated with multiple values. You thus will need to check if the id appears in the QueryDict, perhaps validate that it occurs only once, and check if it is numerical (or some other format).
While it is possible to work with a query string. Usually the idea is in Django that if a parameter is required, you somehow encode it in the path, not in the query string. The query string is normally used for optional data, for example to filter a list.
- 443,496
- 30
- 428
- 555