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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How about this path('foo/bar/<str:barId>', 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
It should work, the kwargs will be in self.request.kwargs so you can write your own logic on handle_{0}_bar methods.
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/<str:barId>. Basically we need to get the end of the Url excluding the path parameter in Url.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.