Takashi Otaka, "Learning by Moving! Introduction to Python Django Development" I'm a beginner who started learning python and Django. I've been studying programming for about 4 months using ruby / rails, When I changed jobs as an engineer, I decided to use python, so I started studying with this book in my hand. Since I am a de-class amateur, I would be very grateful if you could comment on supplements and suggestions.
Like the before_action I used to create the rails app, Insert a fixed process before the specified general view. I also wanted to do this with django.
In particular,,,, Check if the session has a specific value before displaying the template in the class-based generic view. → Yes: Display as it is → None: Redirect to index screen I want to process it.
If you can confirm that you are logged in with @login_required, Maybe I can make something similar ...? No, it can't be done. ↓ Apparently, "@ ~" is a decorator. And after all it seems that you can make your own.
This time, "whether there is a specific value in the session".
def is_hoge_in_session(func):
def hoge_checker(request):
if 'hoge' in request.session:
return func(request)
else:
return redirect("hogeApp:index")
return hoge_checker
Regarding the contents of the code, I wonder if the explanations of the great ancestors are easy to understand. ・ [Python] Explanation of decorators for beginners -How to use Decorator in Django and how to make it
# method_Import decorator
from django.utils.decorators import method_decorator
、、、(Omission)、、、
@method_decorator(is_hoge_in_session, name='dispatch')
class HogeFugaView(LoginRequiredMixin, generic.ListView):
、、、(The following is omitted)
By the way, regarding how to handle function decorators in a class-based view We received wisdom from the following site. [Django] How to use function decorators in class-based views
Time that was thrown away in the dove → 2 hours Impressions: → Even if you are a beginner, even if you do not have a senior who is a specialist in the language you are developing All right, I have a google professor. The rest is enthusiastic.
· [Django] How to use function decorators in class-based views ・ [Python] Explanation of decorators for beginners -How to use Decorator in Django and how to make it
Recommended Posts