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
CodePudding user response:
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.