How to disable authentication altogether for Django admin

拥有回忆 提交于 2020-01-23 02:46:07

问题


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')


来源:https://stackoverflow.com/questions/42141017/how-to-disable-authentication-altogether-for-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!