1

I'm building an Django project demonstration that has in its constitution 3 apps (app, blog, frontend) enter image description here

The challenge I'm facing is the following:

I want to limit access to the app app to allow only registered users.

In other words, restrict access to all the pages in app django app.

After doing some research, stumbled accross the following links:

  1. Link 1
  2. Link 2
  3. Link 3

The answer in Link 1 seems the easier to implement.

Still, I'm having some problems doing it, as I have little experience working with Middleware in Django.

Asked there in the comments:

'I want to limit the access of one app, called app, if the user doesn't have login. The middleware RequireLoginMiddleware class should be placed where?'

but no reply yet so far and I don't seem to find a way to cross this.

Can anyone explain me what I need to do to Restrict access to all the pages in a django app to allow only registered users?

Community
  • 1
  • 1
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145

2 Answers2

2

Where your middleware lives is up to you, the only thing that matters is that it's in your sys.path.

Also note that the middleware in Best way to make Django's login_required the default is relying on hard-coded urls (well, hardcoded in the settings at least), which is a DRY violation. This could be solved by using reverse_lazy for each url of your app app but at this point you'll be faster just decorating your app views with login_required

Community
  • 1
  • 1
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
2

How to fix:

Inside of views.py, from the app app directory, added the following:

from django.contrib.auth.decorators import login_required

and, right before calling the view:

@login_required(login_url="/admin/") #location where users are going to be able to do the login
def profile(request): #view

This means: once the user is not logged on and tries to access the view, he/she/it will be redirected to the login screen

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
  • Don't hardcode urls (use `reverse()` instead). Also, you don't need to specify the login_url in each and any call to `login_required`, if you don't it will use the one specified in your settings (which is usually what you want). – bruno desthuilliers Mar 06 '17 at 15:38
  • Tried to implement `reverse`and `reverse_lazy`. Didn't manage to do it yet and tbh I'm not seeing the importance of it unless you explain better. About the other side, it was made on purpose just to show how that can be done to whatever url we want – Tiago Martins Peres Mar 06 '17 at 17:09