DRF- Django Rest Framework re_path query params - "Method \"GET\" not allowed."

Viewed 830

I've been trying to GET on generics RetrieveAPIView class using the re_path method in urls.py file. After trying several combinations, I can only get the path method to work. I would like to get an endpoint something similar to /file?id={some_uid}.

So far I have the following:

  • django: 3.0.6
  • djangorestframework=3.11.0

views.py:

class UploadFileInfoView(generics.RetrieveAPIView):
    lookup_field = "id"
    queryset = Upload.objects.all()
    serializer_class = UploadModelSerializer

urls.py:

from django.urls import path, re_path
from . import views

urlpatterns = [
    path("file/", views.UploadFileView.as_view(), name="UploadFile"),
    # this works
    # path("file/<uuid:id>", views.UploadFileInfoView.as_view(), name="UploadFileInfo"), 
    # this does not
    re_path(r"^file/(?P<id>[0-9A-Fa-f-]+)", views.UploadFileInfoView.as_view(), name="UploadFileInfo"),
]

Have not used url method as the documentation says

This function is an alias to django.urls.re_path(). It’s likely to be deprecated in a future release.

1 Answers

As far as I know, Query param is passed to the django views by default. So you don't need to handle it explicitly in the URL. In your case if you want /file?id={some_uid} , you should handle it in the view or overwrite the get_queryset method.

urls.py

urlpatterns = [
# ** your other urls **
    path(r"file", views.UploadFileInfoView.as_view(), name="UploadFileInfo"),
]

views.py

class UploadFileInfoView(generics.ListAPIView):
    lookup_field = "id"
    queryset = Upload.objects.all()
    serializer_class = UploadModelSerializer

    def get_queryset(self):
        return Upload.objects.get(id=self.request.GET.get('id'))

the above setup will work for /file/?id=1234 and return Upload.objects.get(id=1234). I have not tested this code but it should work and also you need to handle exception if the object is not present.

Related