Skip to content Skip to sidebar Skip to footer

How Do I Write A Decorator For My Django/python View?

Here's my view. Basically, it returns different Responses based on whether it's logged in or not. @check_login() def home(request): if is_logged_in(request): return x

Solution 1:

Use only @check_login instead of check_login() - otherwise your decorator has to return a decorate as you are doing home = check_login()(home)

Here's an example decorator:

defcheck_login(method):
    @functools.wraps(method)defwrapper(request, *args, **kwargs):
        if request.META['username'] == "blah"
            login(request, user) # where does user come from?!return method(request, *args, **kwargs)
    return wrapper

This decorator will call execute your login function if the username field is set to "blah" and then call the original method.

Solution 2:

A plain decorator is simply a function that takes a function or class and returns something else (usually the same type, but this is not required). A parametrized decorator is a function that returns a decorator.

So, with that in mind we create a closure and return it:

defcheck_login(func):
  definner(request, *args, **kwargs):
    if request.META['username'] == 'blah':
      login(request, user) # I have no idea where user comes from
    func(request, *args, **kwargs)
  return inner

Solution 3:

Here is a decorator I wrote to check if the user is in a certain group. It shows a bit more.

https://github.com/mzupan/django-decorators/blob/master/auth.py

You use it like

@group_required(["group1", "group2"])defshow_index(request):
    view_code_here

The user can be in either group1 or group2 if they are not they get a 404 page

Post a Comment for "How Do I Write A Decorator For My Django/python View?"