Search code examples
pythondjangodjango-viewsdjango-appsdjango-middleware

Django: Block access to specific users in one app


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?


Solution

  • 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