如何完全禁用Django管理界面的身份验证

4
我有一个使用PostGis的Django服务器,我想禁用与身份验证相关的所有内容:
  • 在进入管理界面时不需要进行身份验证
  • 在管理界面中隐藏用户/组
在网上搜寻后,我尝试了这个这个的组合。它确实给我带来了期望的结果,但是当我尝试通过管理界面添加对象时,我会遇到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".

我尝试使用像这个的解决方案来解决问题,但没有帮助。
只要达到最终目标,我不介意采用全新的方法来解决问题。
提前致谢。

3
您需要创建一个ID为1的用户。 - Daniel Roseman
1个回答

4
由于Django项目在docker中运行,且可以在用户存在或不存在时部署,因此我最终进行了以下操作:
# 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')

希望这能帮助到有需要的人。完整用法:
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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接