Using Decorators in Django

Using Decorators in Django

Today I learned about decorators in Django. It was so much fun! Decorators come in several forms in Django, but specifically I worked with them inside of Django's "views" functionality.

Basically, a decorator is like a higher order function that "can be used to access views based on the request method. A message called "django.httpresponse.HttpResponseNotAllowed" , with a 405 status code, will be returned if the conditions to access the views based on the request method are not met. I am including a picture from the Django codebase because my mentor and I have been working on interfaces and on what it means to understand the code just by looking at it and not to necessarily have to go and read the documentation on it. Therefore, please take a look at the code below that I have stolen from the Django website, and hopefully that will help to understand it. I hope that this blog post has been helpful, thank you. I have really enjoyed working with decorators and really enjoyed learning them today.

 
Neon pictures of lights and sparkles in the background: Text reads choose which HTTP methods you allow: view decorators in Django.

A higher order function is a function that takes in another function.

Django view decorators provide a simpler syntax for doing this.

from django.views.decorators.http import require_http_methods


@require_http_methods(["GET", "POST"])
def my_view(request):
    # I can assume now that only GET or POST requests make it this far
    # ...
    pass

Comments

Popular Posts