Common processing when requesting to Class-based View

When implementing Class-based view in Django, it is processed in common whether it is get or post. I wanted to, so I implemented it.

Implementation

If you have a request for get or post, [dispatch ()](https://docs.djangoproject.com/en/1.11/ref/class-based-views/base/#django.views.generic.base Called via .View.dispatch). So I wrapped dispatch () using method_decorator.

def some_decorator(dispatch):
    def wrapper(request, *args, **kwargs):
        # ...Something common processing

        return dispatch(request, *args, **kwargs)

    return wrapper


@method_decorator(some_decorator, name='dispatch')
class MyView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

Is middleware useless?

If it looks like a simple access log, you can implement middleware. However, I wanted to guarantee that it was after all the middleware had been executed, and I wanted to log only a specific View.

Shouldn't I extend View and override dispatch?

If you really want to implement it with only a specific (single) View, you can override it. However, when implementing View, it is actually TemplateView, ListView, DetailView, ModelViewSet of django-rest-framework, so I wanted to implement common processing with them.

version

Django==1.11

Recommended Posts

Common processing when requesting to Class-based View
Django class-based view
Things to keep in mind when processing strings in Python2
Things to keep in mind when processing strings in Python3
Consider common pre-processing when processing DynamoDB Stream with Lambda (Python)
What I was addicted to when migrating Processing users to Python