Search code examples
pythondjangofunctiondecoratorpython-decorators

How to create a custom decorator in Django?


I'm trying to create a custom decorator in Django but I couldn't find any ways to do it.

# "views.py"

@custom_decorator 
def my_view(request):
    # .......

So, how can I create it in Django? and where should I put it so that I can use it anywhere in my Django project?


Solution

  • You don't have to write your own decorator for this as user_passes_test is already included in Django.

    And there's a snippet (group_required_decorator) that extends this decorator and which should be pretty appropriate for your use case.

    If you really want to write your own decorator then there's a lot of good documentation on the net.

    And well, to (re-) use the decorator just put your decorator in a module on your path and you can import it from any other module.