Reputation: 41
I've recently started with Django and I'm unable to understand how to route the URL based on the value of a 'action' parameter which'll be passed along with some other parameters in the URL. So the goal is to filer out the value of the 'action' parameter and routing the url to seperate views accordingly.
For example..
If the URL is:-
/api/?param1=value¶m2=value&action=status
it should be routed to the status view
if it's
/api/?param1=value&action=add¶m2=value
be routed to the add view
and so on no matter the value and position of the other parameters.
Upvotes: 1
Views: 781
Reputation: 476669
I'm unable to understand how to route the URL based on the value of a 'action' parameter which'll be passed along with some other parameters in the URL.
The part after the question mark (?
) is called the querystring [wiki]. It is not part of the path, hence the Django routing mechanism does not take it into account. You can access these parameters with request.GET
[Django-doc], which is a QueryDict
object [Django-doc]. A QueryDict
is a dictionary-like object, but a key can map to multiple values.
You will need to perform the correct action in the view itself. So you can implement a path like:
# myapp/urls.py
from django.urls import path
from myapp import views
urlpatterns = [
path('api/', views.myapi, name='api')
]
In the view you can then specify how to act accordingly:
# myapp/views.py
def myapi(request):
if request.GET.get('action') == 'add':
# …
pass
if request.GET.get('action') == 'status':
# …
pass
# …
However in Django web applications, often the action is part of the path. So one makes urls that look for example like:
api/model1/
api/model1/pk
api/model1/add
Upvotes: 1