What is the opposite of @login_required decorator for Django views?

后端 未结 6 2078
耶瑟儿~
耶瑟儿~ 2020-12-29 09:37

If I want to make sure that a view is listed as having public access, is there a decorator equivalent to @public_access which would be the opposite of @login_required and ma

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 09:53

    As a previous poster mentioned, login not required is the default.

    However, sometimes it's useful to block certain views from logged in users -- for instance, it makes no sense for a logged-in user to be able to use the site's signup page. In that case, you could do something like this, based off the existing login_required decorator

    from django.contrib.auth.decorators import user_passes_test
    from django.conf import settings
    
    LOGGED_IN_HOME = settings.LOGGED_IN_HOME
    
    def login_forbidden(function=None, redirect_field_name=None, redirect_to=LOGGED_IN_HOME):
        """
        Decorator for views that checks that the user is NOT logged in, redirecting
        to the homepage if necessary.
        """
        actual_decorator = user_passes_test(
            lambda u: not u.is_authenticated(),
            login_url=redirect_to,
            redirect_field_name=redirect_field_name
        )
        if function:
            return actual_decorator(function)
        return actual_decorator
    

提交回复
热议问题