I have such a model:
class test (model. Model): is_private = Model Booleanfield (default = False)
I have a view like this:
Class test data view (see): def (self, request, pk) : Return Render (Request, 'test.html', {'story': Story.objects.get (pk = pk)}
So now, what do I do: Apply on different_on_cookie decorator If the test is private, otherwise use the
cache_page
decorator.
How to do this?
The main issue here is that you run Runtime Want to choose the decorator, but the usual decorator syntax has been triggered at the class announcement time. Fortunately, decorators are just regular Python calls, so that you can apply them to runtime if you want.
Note that, as discussed, one CBV is the correct place to apply Django decoration dispatch ()
Method; And you need to use the method_decorator
to create the Django's built-in decorator suitable for the use of classes.
def test_decorator (dispatch_wrapped): def dispatch_wrapper (auto, request, * args, ** kwargs): # You are probably filtering something in the request or url is_private = Test.objects .get (...) Is_private decorator = vary_on_cookie if is_private else cache_page (60 * 15) dispatch_decorated = method_decorator @test_decorator DEF dispatch (self, * args, ** kwargs): (decorator) (dispatch_wrapped) return dispatch_decorated (self, request, * args, ** kwargs ) Dispatch_wrapper class returned TestDetaiView (see) # any custom transmission code, or just ... super (). Removal (* Args, ** Quorz)
If it is misleading, then perhaps it will help to read more about decoration and how it is defined and used.
No comments:
Post a Comment