Reputation: 6555
I'm trying to write my first middleware in Django.
class RefreshBalance:
def process_view(self, request, view_func, view_args, view_kwargs):
pass
I want to detect if a view is called and refresh a balance. I can see the 'view' argument but don't know how to I use it? For example:
if view == "login.dashboard:
pass
How can I find out what view is being called?
Upvotes: 4
Views: 3720
Reputation: 2358
To answer the question:
I can see the 'view' argument but don't know how to I use it?
Then you are not using the power and beauty of python.
try this this:
breakpoint()
if view == "login.dashboard:
pass
This will pause execution, and allow you to interact with python, at that point in code.
Once it pauses execution, the first I do is type list<ENTER>
to list the code around where it stopped, just to orientate oneself.
Wish to see what type of object view
is? Type type(view)
, and now you know!
Want to know what methods and attributes it has, dir(view)
, and now you know. Or pp dir(view)
to pretty print it.
Oh it has a foo_very_interesting_method
, try:
solong = view.foo_very_interesting_method
help(solong)
If you lucky it will print some helpful info.
Want to see the value of view.bar_attribute, type view.bar_attrbiute
, and its printed for you.
When done playing type c
to continue, q
to quit, n
to goto the next line, or s
to step.
And theres a whole lot more if you research python debugger
.
Enjoy being able to figure out what is going on!
Upvotes: -1
Reputation: 7631
From the middleware documentation:
process_view(self, request, view_func, view_args, view_kwargs) request is an HttpRequest object. view_func is the Python function that Django is about to use. (It’s the actual function object, not the name of the function as a string.)
So you need to do something like:
from login import dashboard
if view_func.__name__ == dashboard.__name__:
pass
Upvotes: 2