Skip to main content
 首页 » 编程设计

python之如何为 Django 管理员完全禁用身份验证

2024年08月21日33bonelee

我有一个 Django 服务器(使用 PostGis),我想禁用与身份验证相关的所有内容:

  • 进入管理员时不需要身份验证
  • 在管理员中隐藏用户/组

在网上搜索后我尝试了this的组合& this

它确实让我得到了我希望的结果,直到我尝试通过管理员添加一个对象。然后我得到一个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". 

我尝试使用类似 this 的解决方案来解决它但这没有帮助。

只要达到最终目标,我不介意采用全新的方法来解决问题。

谢谢,

请您参考如下方法:

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