How to write a Coustom Decorater in Django Project...
Firstly as it is Django, It has a different structure than Codeigniter.
After Creating an App in Django we have some models (Database tables) that are default created like user tables and can be modified.
Let's come to the point of Decorates, These are used for authenticating any user or a client using our URLs, it's possible to use whether to allow user to run that function or not .
Custom Decorator is like validating or authenticating users with our conditions.
step 1: Create a file named decorator.py in any of the apps.
step 2: create a function with any of your likely decorator names.
def Decorator_name(function)
step 3: In that function create a wrap function.
def wrap(request, *args, **kwargs):
step 4: Write your condition to get validate a user and return the value as valid or raise an error code by this step, This function is converted as a Decorator now.
entry = #(Any Condition that will return true if Valid and False if not). if entry: #IF IT'S TRUE return function(request, *args, **kwargs) else: # raise an Error Code raise PermissionDenied
step 5: Import that file and call our Decorator on top of any function to validate.
from App.decorators import *
Example: (you can use this as a decorator for live by coping).
creating Decorate:
from django.core.exceptions import PermissionDenied def Decorator_name(function): def wrap(request, *args, **kwargs): try: entry = #(Any Condition that will return true if Valid and False if not). if entry: #IF IT'S TRUE return function(request, *args, **kwargs) else: # raise an Error Code raise PermissionDenied except: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap
Calling a decorator:
from App.decorators import * from django.http.response import HttpResponse, JsonResponse @Decorator_name def testingfunction(request): response={} return JsonResponse(response,safe=False)
Thank you, Hope this post helps you.