Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom decorator to pass custom data to function in Django

I want to create custom decorator that checks current user and run a query for this user to get some data that belongs him and then if has defined data function is called with whole list passed else returns 403 error.
How can i approach this?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can write decorator like this:

# check_data is what the user must have access to
def custom_decorator(check_data):
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            user = request.request.user
            # data_list is list of his access
            data_list = []
            if user.is_authenticated:
                pass
                # you can do your query here to check access
            
            if check_data in data_list:
                kwargs['access_list'] = data_list
                return func(request, *args, **kwargs)
            
            # return Http Error here

        return wrapper

    return decorator

Add access_list parameter to your view function:

@custom_decorator("something")
def get(self, request, access_list=None):
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading