【问题标题】:How to disable authentication altogether for Django admin如何为 Django 管理员完全禁用身份验证
【发布时间】:2017-02-09 15:46:19
【问题描述】:

我有一个 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 之类的解决方案解决它,但没有帮助。

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

谢谢,

【问题讨论】:

  • 您需要实际创建一个 id=1 的用户。

标签: python django django-rest-framework postgis


【解决方案1】:

由于 Django 项目在 dockers 中运行,并且可以在用户已经存在或不存在时部署:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2019-07-16
    • 1970-01-01
    • 2015-03-23
    • 2011-09-18
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多