I'm trying to form a url like this,
http://localhost:8000/mealplan/meals/search/2?from_date=2019-12-29&to_date=2019-12-30&from_time=06:00&to_time=22:00
This is what I tried in urls.py
url(r'^meals/search/(?P<user_id>[\w.-]+)/(?P<from_time>[\w.-]+)/(?P<to_time>[\w.-]+)/(?P<from_date>[\w.-]+)/(?P<to_date>[\w.-]+)$', FilterMealList.as_view(), name='filter_meals'),
Clearly this didn't work. I got a 404, url doesn't exist on postman. Also this is my class based view.
class FilterMealList(views.APIView):
def get(self, request, **kwargs):
try:
from_time, to_time, from_date, to_date = kwargs.get('from_time'), kwargs.get('to_time'), kwargs.get(
'from_date'), kwargs.get('to_date')
return Response({"Suceess": "{}, {}, {}, {}".format(from_time, to_time, from_date, to_date)},
status=status.HTTP_200_OK)
except KeyError as e:
return Response({"Failure": "Incomplete query params"}, status=status.HTTP_400_BAD_REQUEST)
So my question, 1. How do I define an url to take query params in django? 2. How do I capture the params in my class based view?
How can I create an url to take query params in django
Use request.GET to get a dictionary of the query params. The params shouldn't be defined in urls.py.
See the docs: https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest.GET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With