How to disable authentication altogether for Djang

2020-07-22 10:15发布

问题:

I have a Django server (Using PostGis) and I want to disable everything related to authentication:

  • When entering the admin no authentication will be required
  • In the admin hide the Users/Groups

After searching online I tried the combination of this & this

It does get me the result I hoped for, until I try to add an object via the admin. Then I get an IntegrityError:

insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id"
DETAIL:  Key (user_id)=(1) is not present in table "auth_user".

I tried solving it using solutions like this and it didn't help.

I don't mind having a solution in a whole new approach as long as the end goal is acquired.

Thanks ahead,

回答1:

As the Django project is running in dockers, and can be deployed when the users already exist or don't I ended up doing:

# Create superuser for admin use in case it doesn't exist
try:
    User.objects.get_by_natural_key('admin')
except User.DoesNotExist:
    User.objects.create_superuser('admin', 'admin@comapny.com', '123456')

Hope this helps someone one day. Full use:

from django.contrib import admin
from django.contrib.auth.models import User, Group


# We add this so no authentication is needed when entering the admin site
class AccessUser(object):
    has_module_perms = has_perm = __getattr__ = lambda s,*a,**kw: True

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

# We add this to remove the user/group admin in the admin site as there is no user authentication
admin.site.unregister(User)
admin.site.unregister(Group)

# Create superuser for admin use in case it doesn't exist
try:
    User.objects.get_by_natural_key('admin')
except User.DoesNotExist:
    User.objects.create_superuser('admin', 'admin@optibus.co', '123456')