Alex Rivera | Logout

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

Asked 2010-02-12T18:51:23.170
17

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 make it clear that the view should be publicly accessible always?

One use case I have in mind is to automatically add "@csrf_exempt" to all public views in addition to making it clear in the code that the view should be publicly accessible.

Edit
Report

1 Answer

7

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
answered 2011-08-15T22:03:14.523

Your Answer