santosh
santosh

Reputation: 4149

Django use custom method name in Django class view

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.

Upvotes: 1

Views: 964

Answers (1)

Patryk Szczepański
Patryk Szczepański

Reputation: 784

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.

Upvotes: 1

Related Questions