A story that I wanted to do a function like before_action used in rails with django [Beginner learns python with a reference book]

Introduction

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.

Overview

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.

Consideration

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.

Describe the processing you want to perform in common.

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

Just place it on top of the target class view.

# 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

This summary

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.

Great reference article

· [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

A story that I wanted to do a function like before_action used in rails with django [Beginner learns python with a reference book]
A story that I wanted to display the division result (%) on HTML with an application using django [Beginner learns python with a reference book in one hand]
I made a familiar function that can be used in statistics with Python
A story that I did not know how to load a mixin when making a front with the django app [Beginners learn python with a reference book in one hand]
A story that didn't work when I tried to log in with the Python requests module
order_by ('-created_at') ← What is "ー"? ?? ?? [Beginner learns python with a reference book]
A story that I was addicted to when I made SFTP communication with python
I want to work with a robot in python.
A story that required preparation when trying to do a Django tutorial with plain centos7
I wanted to create a dll to use a function written in C from Python with ctypes, but I had a hard time
A story that went missing when I specified a path starting with a tilde (~) in python open
I made a program to collect images in tweets that I liked on twitter with Python
I made a puzzle game (like) with Tkinter in Python
I also tried to imitate the function monad and State monad with a generator in Python
I want to use a wildcard that I want to shell with Python remove
[Road to Python Intermediate] Call a class instance like a function with __call__
[Python] A memo that I tried to get started with asyncio
I want to do a full text search with elasticsearch + python
I wrote a function to load a Git extension script in Python
I wanted to solve the ABC164 A ~ D problem with Python
I want to improve efficiency with Python even in an experimental system (3) I want to do something like Excel with Pandas
I made a web application in Python that converts Markdown to HTML
It's more recent, but I wanted to do BMI calculation with python.
I tried to develop a Formatter that outputs Python logs in JSON
I want to do a monkey patch only partially safely in Python
I used Python with the minimum necessary knowledge, but I bought a reference book and studied again to summarize what I learned new and what I found useful.
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
I wanted to solve ABC160 with Python
I wanted to solve ABC159 in Python
I wanted to solve ABC172 with Python
I wanted to quickly create a mail server that can be used freely with postfix + dovecot on EC2
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
A story about converting HTML to PDF with WeasyPrint + matplotlib and embedding graphs [Beginners learn python with a reference book]
I tried to create a class that can easily serialize Json in Python
A confusing story with two ways to implement XGBoost in Python + overall notes
I want to create a priority queue that can be updated in Python (2.7)
A story that turned light blue in 4 months after starting AtCoder with python
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
[Beginner] What happens if I write a program that runs in php in Python?
Introducing the book "Creating a profitable AI with Python" that allows you to learn machine learning in the shortest course
I want to do Dunnett's test in Python
A memo that I wrote a quicksort in Python
I wanted to solve NOMURA Contest 2020 with Python
I wanted to install Python 3.4.3 with Homebrew + pyenv
I want to write to a file with Python
[Mac] I want to make a simple HTTP server that runs CGI with Python
I want to save a file with "Do not compress images in file" set in OpenPyXL
A beginner tried coloring line art with chainer. I was able to do it.
I tried to make a function to judge whether the major stock exchanges in the world are daylight saving time with python
When writing to a csv file with python, a story that I made a mistake and did not meet the delivery date
How to convert / restore a string with [] in python
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I made a Twitter BOT with GAE (python) (with a reference)
I want to transition with a button in flask
I tried to draw a route map with Python
I want to write in Python! (2) Let's write a test
I tried to implement a pseudo pachislot in Python
I want to randomly sample a file in Python
I was addicted to scraping with Selenium (+ Python) in 2020
I tried to automatically generate a password with Python3