Django Admin without Authentication
The accepted answer adapted for Django version >= 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)
In [yourproject]/settings.py
for the MIDDLEWARE
list:
- Comment or remove:
'django.contrib.auth.middleware.AuthenticationMiddleware',
- Append:
'[yourapp].middleware.AuthenticationMiddleware',
Probably obvious to most people but note that the solution still requires one user to exist. Create one manually python manage.py createsuperuser
or automatically with a script:
- How to automate createsuperuser on django?
- Autocreate superuser with each schema django
- Create django super user in a docker container without inputting password
Create a module auto_auth.py
:
from django.contrib.auth.models import User
from django.utils.deprecation import MiddlewareMixin
class AutoAuthMiddleware(MiddlewareMixin):
def process_request(self, request):
request.user = User.objects.filter()[0]
Edit MIDDLEWARE
in your settings.py
:
- Remove
'django.contrib.auth.middleware.AuthenticationMiddleware'
- Add
'auto_auth.AutoAuthMiddleware'
You can change User.objects.filter()[0]
to something else if you want a particular user.
In response to your comment: yes. To run the Django admin without users at all, try this:
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 AutoAuthMiddleware(MiddlewareMixin):
def process_request(self, request):
request.user = User()
And remove 'django.contrib.auth'
from INSTALLED_APPS
But if you use any apps that depend on the auth app, you're going to have a bad time.
The accepted answer is already super simple however after messing around with this I found that in recent versions of Django (since admin.site.has_permission became a thing... >= 1.8?) you can do it without middleware.
In your project's 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),
]
If you have AccessUser extend User you can leave out the __getattr__
portion which is a hacky way to return something when user.pk or similar is called.