1

I have Url like /foo/bar and Class based view has been defined as below.

class FooBar(View):
    
   def handle_post_bar(self, request):
     pass

   def handle_get_bar(self, request):
     pass

   def handle_put_bar(self, request):
     pass

In url i define as path('foo/bar/', FooBar.as_view())

Based on the http method and path i would like build view method names ex: handle_{0}_{1}'.format(method, path) Please suggest me how to achive this, this should be common to all the urls and views. i tried exploring the possibility of django middleware, but endedup in no luck.

santosh
  • 3,947
  • 3
  • 21
  • 32

1 Answers1

1

Okey, it's certainly possible, you should write your logic like this:

class FooBar(View):
    func_expr = 'handle_{0}_bar'

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        method = request.method.lower()
        func = self.func_expr.format(method)
        if hasattr(self, func):
            return getattr(self, func)(request)
        raise Http404

    def handle_post_bar(self, request):
        print('POST')
        return JsonResponse({'result': 'POST'})

    def handle_get_bar(self, request):
        print('GET')
        return JsonResponse({'result': 'GET'})

    def handle_put_bar(self, request):
        print('PUT')
        return JsonResponse({'result': 'PUT'})

It works for me:

enter image description here

Generally things like this you code on method called dispatch. If you want to achieve it on more views (not only one) without repeating code, you should write own mixin that uses this logic.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Patryk Szczepański
  • 731
  • 1
  • 4
  • 12
  • How about this path('foo/bar/', FooBar.as_view()) this should still resolve to method in view based on http method and also barId as any Kwargs for method. which means if there is any method with kwargs, same as defined in Url and also if http method matches, then it should resolve accordingly – santosh Aug 03 '22 at 18:25
  • It should work, the kwargs will be in `self.request.kwargs` so you can write your own logic on `handle_{0}_bar` methods. – Patryk Szczepański Aug 03 '22 at 18:57
  • Url will be some thing like `/foo/bar` and method will be of format `handle_{0}_{1}.format(method, end_point)` so we need to get end point as `bar`, current implementation is `uri_path = request.path end_point =uri_path.strip('/').split('/')[-1]` but incase of url like `/foo/bar/12345` where `12345` is path parameter, in urls ir will be defined as `/foo/bar/`. Basically we need to get the end of the Url excluding the path parameter in Url. – santosh Aug 04 '22 at 05:09