title: LDAP authentication using django
body: <p>Could anyone of you please help me to implement LDAP authentication using Django. I want to develop a web application which should allow users to access the application post LDAP authentication. I have coded the basic things but I get some failures.</p>
  
  <p>Settings.py </p>
  
  <pre><code>"""
  Django settings for HandBook project.
  
  Generated by 'django-admin startproject' using Django 2.1.7.
  
  For more information on this file, see
  https://docs.djangoproject.com/en/2.1/topics/settings/
  
  For the full list of settings and their values, see
  https://docs.djangoproject.com/en/2.1/ref/settings/
  """
  
  import os
  import ldap
  from django_auth_ldap.config import LDAPSearch
  # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  AUTH_LDAP_SERVER_URI = "serverIp"
  AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend')
  AUTH_LDAP_CONNECTION_OPTIONS = {
      ldap.OPT_REFERRALS: 0
  }
  # Quick-start development settings - unsuitable for production
  # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
  
  # SECURITY WARNING: keep the secret key used in production secret!
  SECRET_KEY = '4xkkb*m!&amp;@^xzhkpe6#gxe@xeee0ug3q0h$@-)#lv8+0dqpid*'
  
  # SECURITY WARNING: don't run with debug turned on in production!
  DEBUG = True
  
  ALLOWED_HOSTS = ["192.168.113.75"]
  
  
  # Application definition
  
  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'NewHandBook.apps.NewhandbookConfig',
  ]
  
  MIDDLEWARE = [
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
  ]
  
  ROOT_URLCONF = 'HandBook.urls'
  
  TEMPLATES = [
      {
          'BACKEND': 'django.template.backends.django.DjangoTemplates',
          'DIRS': [os.path.join(BASE_DIR, 'templates')]
          ,
          'APP_DIRS': True,
          'OPTIONS': {
              'context_processors': [
                  'django.template.context_processors.debug',
                  'django.template.context_processors.request',
                  'django.contrib.auth.context_processors.auth',
                  'django.contrib.messages.context_processors.messages',
              ],
          },
      },
  ]
  
  WSGI_APPLICATION = 'HandBook.wsgi.application'
  
  
  # Database
  # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
  
  DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.sqlite3',
          'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      }
  }
  
  
  # Password validation
  # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
  
  AUTH_PASSWORD_VALIDATORS = [
      {
          'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
      },
  ]
  
  
  # Internationalization
  # https://docs.djangoproject.com/en/2.1/topics/i18n/
  
  LANGUAGE_CODE = 'en-us'
  
  TIME_ZONE = 'UTC'
  
  USE_I18N = True
  
  USE_L10N = True
  
  USE_TZ = True
  
  
  # Static files (CSS, JavaScript, Images)
  # https://docs.djangoproject.com/en/2.1/howto/static-files/
  
  STATIC_URL = '/static/'
  </code></pre>
  
  <p>Views.py</p>
  
  <pre><code>from django.shortcuts import render
  from django.contrib.auth import authenticate, login
  from django.template import RequestContext
  from django.shortcuts import render_to_response
  
  
  def login(request):
      return render(request, 'login/login.html')
  
  
  def login_user(request):
      username = password = ""
      state = ""
  
      if request.POST:
          username = request.POST.get('username')
          password = request.POST.get('password')
  
          print(username, password)
  
          user = authenticate(username=username, password=password)
          if user is not None:
              login(request, user)
              return render(request, 'login/base.html', {'state': state, 'username': username})
          else:
              return render(request, 'login/login.html', {'state': state, 'username': username})
  )
  </code></pre>
  
  <p>login.html</p>
  
  <pre><code>    {% extends 'login/base.html' %}
  {% load static %}
  
  &lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;Login&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  {% block body %}
      &lt;form method="post" action="/NewHandBook/validate/"&gt;{% csrf_token %}
          &lt;div class="container"&gt;
              &lt;div class="row"&gt;
                  &lt;div class="col-md-10 offset=md-1"&gt;
                      &lt;div class="row"&gt;
                          &lt;div class="col-md-5 register-left "&gt;&lt;br&gt;&lt;br&gt;
                              &lt;img style="width: 350px;position: absolute;margin-left: -350px;margin-top: -80px"
                                   src="{% static 'images/gar.png' %}"&gt;
                              &lt;h1 style="font-family: Brush Script MT;font-size: 70px;margin-top: 45px;margin-left: -342px"&gt;
                                  HandBook.&lt;/h1&gt;
                              &lt;p style="font-family: Courier New;margin-top: -20px;margin-left: -359px "&gt;&lt;i
                                      class="fas fa-shield-alt"&gt;&lt;/i&gt; Secure &lt;i
                                      class="far fa-share-square"&gt;&lt;/i&gt; Share &lt;i class="far fa-smile-beam"&gt;&lt;/i&gt; Smile
                              &lt;/p&gt;
  
                          &lt;/div&gt;
  
                          &lt;div class="col-md-7 register-right"&gt;
                              &lt;h2 style="font-family: Courier;color: azure"&gt;Login Here&lt;/h2&gt;
                              &lt;h7 style="font-family: Courier;font-size: 13px;color: aliceblue"&gt;
                                  &lt;h7 style="color: red"&gt;*&lt;/h7&gt;
                                  Please use your system credentials
                              &lt;/h7&gt;
                              &lt;div class="register-form"&gt;
                                  &lt;div class="form-group"&gt;
                                      &lt;input type="text" name="username" class="form-control" placeholder="User name"
                                             style="font-family: Courier"&gt;
  
                                  &lt;/div&gt;
                                  &lt;div class="form-group"&gt;
                                      &lt;input type="password" name="password" class="form-control" placeholder="Password"
                                             style="font-family: Courier"&gt;
  
                                  &lt;/div&gt;
                                  &lt;input type="reset" class="btn btn-primary" value="Reset"&gt;
                                  &lt;button type="submit" class="btn btn-primary"&gt; Login Now&lt;/button&gt;
  
                              &lt;/div&gt;
  
                          &lt;/div&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/form&gt;
  {% endblock %}
  &lt;/body&gt;enter code here
  &lt;/html&gt;## Heading ##
  </code></pre>
  
  <p>I get below error when i run my project
  <a href="https://i.stack.imgur.com/eZeIK.png" rel="nofollow noreferrer">exception</a></p>
  
  <p>Could anyone of you please help me here.</p>
  
  <p>My use case:
  user should be able to land on some home page after a successful login or should land back on same login page if provided credentials are invalid.</p>