I have a class based view and that has method post as follows
class Comment(View):
def dispatch(self, request, *args, **kwargs):
super(Comment, self).dispatch(request, *args, **kwargs)
@method_decorator(transaction.non_atomic_requests)
def post(self, request, *args, **kwargs):
<Some code>
In above example transaction.non_atomic_requests does not make post method non atomic, but if I use same decorator for dispatch method then it works? Why?
I am using django 1.9
When you use the transaction.non_atomic_requests
decorator, it sets an attribute _non_atomic_requests
on the decorated object.
Django then checks for the _non_atomic_requests
attribute when the view runs.
When Django runs a class based view, it doesn't run the dispatch
method directly, it runs the view that is returned by the as_view()
method.
There is code in the as_view()
method that copies attributes like _non_atomic_requests
from the dispatch
method to the view that is returned.
However the as_view
method does not copy attributes from any other methods like get
or post
. When you decorate the post
method, the _non_atomic_requests
attribute is not copied to the view, so the decorator does not work.
Therefore, you must apply decorators like transaction.non_atomic_requests
or csrf_exempt
to the dispatch
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With