user10309179
user10309179

Reputation:

Django URL, pass parameters in URL

I want to create url like:

/api/foodfeeds/?keywords=BURGER,teste&mood=happy&location=2323,7767.323&price=2

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api/foodfeed/(?P<keywords>[0-9.a-z, ]+)/(?P<mood>[0-9.a-z, ]+)/(?P<location>[0-9]+)/(?P<price>[0-9]+)/$', backend_views.FoodfeedList.as_view()),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

views.py

class FoodfeedList(APIView):
    # permission_classes = (permissions.IsAuthenticated,)
    def get(self,request,keywords,mood,location,price):
        print(request.GET['keywords'])

Upvotes: 0

Views: 1220

Answers (2)

JPG
JPG

Reputation: 88499

As @Umair said, you're passing those keys as URL query parameters, so you don't have to mention it in URLPATTERNS

In your case, to get the data you're passing through the URL, follow the below code snippet

#urls.py
urlpatterns = [
                  path('admin/', admin.site.urls),
                  url(r'^api/foodfeed/', backend_views.FoodfeedList.as_view()),
              ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


#views.py
class FoodfeedList(APIView):
    # permission_classes = (permissions.IsAuthenticated,)
    def get(self, request):
        print(request.GET) # print all url params
        print(request.GET['keywords'])
        print(request.GET['mood'])
        # etc

Upvotes: 4

Umair Mohammad
Umair Mohammad

Reputation: 4635

Those keywords, mood, location, etc are query params you should not include those in url, rather you should access them via request.query_params

Reference : http://www.django-rest-framework.org/api-guide/requests/#query_params

Upvotes: 2

Related Questions