[Answered ]-Django use custom method name in Django class view

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.

Leave a comment