0

I am using Django-auth-LDAP for authentication, now I want to get data for a field like :

AUTH_LDAP_BIND_DN, AUTH_LDAP_BIND_PASSWORD, AUTH_LDAP_SERVER_URI

from the database but I am getting an error.

settings.py

import subprocess
from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
ldap = False
Config = apps.get_model('config', 'Config')
Config = Config()
try:
    ldap = Config.objects.get(name="ldap")
except ObjectDoesNotExist:
    pass
if ldap and check_ldap_connection():
    import ldap
    from django_auth_ldap.config import LDAPSearch
    AUTH_LDAP_SERVER_URI = Config.objects.get(name="ldap_server_uri")

    AUTH_LDAP_BIND_DN = Config.objects.get(name="ldap_bind_dn")
    AUTH_LDAP_BIND_PASSWORD = Config.objects.get(name="ldap_bind_password")
    ldap_search = Config.objects.get(name="ldap_search")
    AUTH_LDAP_USER_SEARCH = LDAPSearch(
        ldap_search , ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
    )

def check_ldap_connection():
    try:
        ldap_server_uri = Config.objects.get(name="ldap_server_uri")
        ldap_bind_dn = Config.objects.get(name="ldap_bind_dn")
        ldap_search = Config.objects.get(name="ldap_search")
        ldap_bind_password = Config.objects.get(name="ldap_bind_password")
    except ObjectDoesNotExist:
        return False
    cmd = "ldapsearch -H \"" + ldap_server_uri + "\" -D \"" + ldap_bind_dn + "\" -w \"" +  ldap_bind_password \
          + "\" -b \"" + ldap_search + "\" | " + "grep result"
    try:
        connection = ""
        connection = subprocess.check_output(cmd, shell=True).decode()
    except Exception as e:
        return False
        connection = connection.split()
        if "0" and "Success" in connection:
            return True
        return False

Error:

raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Phoenix
  • 3,996
  • 4
  • 29
  • 40
Rohit Sharma
  • 372
  • 5
  • 17
  • 1
    dont do that in your settings.py, write that in an init.py or a middleware or call a function on some other file but dont write this kinda logic in your settings.py! To get rid of your error you would need to write `django.setup()` but as I said. Dont – hansTheFranz Sep 12 '19 at 09:35
  • how to write that in middleware or init.py? – Rohit Sharma Sep 12 '19 at 09:59
  • 1
    If you want to store these data in DB, then you can look into https://django-constance.readthedocs.io/en/latest/ – ruddra Sep 12 '19 at 10:47
  • @ruddra hey I try constance database but it is still showing that apps are'nt loaded yet error – Rohit Sharma Sep 19 '19 at 05:47

0 Answers0