Skip to main content
 首页 » 编程设计

python之django > 1.7 中的 django-ldap-auth 用户配置文件

2024年08月21日36bjzhanghao

我正在尝试实现 django-ldap-auth在我的项目中,一切似乎都运行良好。问题是,对于高于 1.7 的 Django 版本,该包不支持 user profile 字段填充。

来自文档:

Note Django 1.7 and later do not directly support user profiles. In these versions, LDAPBackend will ignore the profile-related settings.

我已将此添加到我的 settings.py 但没有任何反应(如预期):
AUTH_LDAP_PROFILE_ATTR_MAP = {"description": "description"}

我的问题是:如何在较新的 django 版本中启用 AUTH_LDAP_PROFILE_ATTR_MAP?

编辑:我正在考虑使用自定义用户模型,但我不确定这是否是这里的最佳方式..

请您参考如下方法:

我使用 一对一 User profile model 和 django-ldap-auth< 发出的 populate_user 信号解决了这个问题.

Code

from __future__ import unicode_literals 
import django_auth_ldap.backend 
from fences.models import Profile 
from django.db import models 
 
def populate_user_profile(sender, user=None, ldap_user=None, **kwargs): 
  temp_profile = None 
  bucket = {} 
 
  try: 
      temp_profile = user.profile 
  except: 
      temp_profile = Profile.objects.create(user=user) 
 
  bucket['street_address'] = ldap_user.attrs.get('streetAddress') 
  bucket['telephone_number'] = ldap_user.attrs.get('telephoneNumber') 
  bucket['title'] = ldap_user.attrs.get('title') 
 
  for key, value in bucket.items(): 
      if value: 
          setattr(user.profile, key, value[0].encode('utf-8')) 
  user.profile.save() 
 
django_auth_ldap.backend.populate_user.connect(populate_user_profile)