[Answered ]-Django – how to restrict number of pages an unauthenticated user can view

2👍

Something like:

if has_attr(request, 'page_count'):
    request.page_count += 1
else:
    request.page_count = 1

From the docs how to implement middleware:

def simple_middleware(get_response):
# One-time configuration and initialization.

def middleware(request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.

    response = get_response(request)

    # Code to be executed for each request/response after
    # the view is called.

    return response

return middleware

Or:

class SimpleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

Edit:
If you are using a class implement it so:

def process_request(self, request):
    if request.page_count >= <count>:
        return redirect(<your redirect here>)

0👍

Yes, a middleware is the right place. Middleware runs on every request and it has access to the current request and session, and the user object if the middleware is run after SessionMiddleware and AuthenticationMiddleware (depends on the order in the MIDDLEWARE_CLASSES setting).

You can save the number of pages seen on the setting, and if it’s over the limit then return a HttpResponseRedirect from the middleware.

Of course the user can always throw away his session cookie or start an incognito browser tab, that can’t be helped.

See the middleware documentation: https://docs.djangoproject.com/en/1.11/topics/http/middleware/ .

Leave a comment