Django admin without authentication

Is there a ready-made way to use the Django admin page without any authentication? I know I can use this method , but that was for Django 1.3. Are there any changes that would allow me to do this more easily in Django 1.6?

My main motivation for this is that I want to have as few database tables as possible, and I only use it locally, so no authentication is needed (I only ever run the server on the local host anyway).

+7
source share
4 answers

Create a module auto_auth.py:

from django.contrib.auth.models import User

class Middleware(object):
    def process_request(self, request):
        request.user = User.objects.filter()[0]

MIDDLEWARE_CLASSES settings.py:

  • 'django.contrib.auth.middleware.AuthenticationMiddleware'
  • 'auto_auth.Middleware'

User.objects.filter()[0] - , , .


: . :

class User:
    is_superuser = True
    is_active = True
    is_staff = True
    id = 1

def return_true(*args, **kwargs):
    return True
User.has_module_perms = return_true
User.has_perm = return_true

class Middleware(object):
    def process_request(self, request):
        request.user = User()

'django.contrib.auth' INSTALLED_APPS

, auth, .

+9

, , , , Django ( admin.site.has_permission -... >= 1,8?), .

urls.py:

from django.contrib import admin

class AccessUser:
    has_module_perms = has_perm = __getattr__ = lambda s,*a,**kw: True

admin.site.has_permission = lambda r: setattr(r, 'user', AccessUser()) or True

# Register the admin views or call admin.autodiscover()

urlpatterns = [
    # Your url configs then...
    url(r'^admin/', admin.site.urls),
]

AccessUser, __getattr__, -, user.pk .

+7

Django> = 1.10

/[yourapp]/middleware.py:

from django.contrib.auth.models import User

class AuthenticationMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        request.user = User.objects.filter()[0]
        return self.get_response(request)  

[yourproject]/settings.py MIDDLEWARE:

  • : 'django.contrib.auth.middleware.AuthenticationMiddleware',
  • : '[yourapp].middleware.AuthenticationMiddleware',

, , , . python manage.py createsuperuser :

+2
source

For newer versions of django> = 2.1, you need to do something like this:

auto_auth.py

class User:
    is_superuser = True
    is_active = True
    is_staff = True
    id = 1
    pk = 1


User.has_module_perms = True
User.has_perm = True


class Middleware(object):
     def __init__(self, get_response):
          self.response = get_response

     def __call__(self, request):
         request.user = User()
         return self.response(request)

And also do not forget to change the settings middleware, disable django.contrib.authand addauto_auth

0
source

Source: https://habr.com/ru/post/1545862/


All Articles