Django request.method自动设置为GET而不是POST

时间:2017-06-23 18:31:38

标签: django python-3.x ldap django-authentication ldap3

我想在Django中设置LDAP身份验证后端,我已经使用ldap3确认绑定,但是成功了。  我现在意识到只用ldap3为我的LDAP后端编写一个类并不是那么简单,而且安装  django_auth_ldap可能是探索的另一条途径。

我已经测试了一些代码来创建绑定到LDAP“服务器”,然后执行简单的搜索。一切都好。我测试的这个方法不在我的Django框架之内。

在我的Django框架中实现相同的方法时,在调用方法时会遇到问题。由于print语句,我知道view被调用为exptected,但是应该执行第一个“if”语句的代码部分不会被调用,除非我从“POST”更改  要得到”。但是这似乎创建了下一个问题(当我设置为“GET”时,所以强制执行下一行),因为我想要一个登录页面然后被调用,然后我可以输入我的LDAP凭据,  最终确认LDAP连接。这是我的代码:

 views.py

 def login_ldap(request):
    LDAP_SERVER = '10.222.4.88'
    searchFilter='random'
    print (request)
    print (LDAP_SERVER)  

print ("request.method:{0}".format(request.method))

if request.method == "GET":
    print ("if statement executed")
    username = request.GET['username']
    print ("U:{0}".format(username))
    password = request.GET['password']
    print ("P:{0}".format(password))

    # Define the server and bind_dn
    server = Server(LDAP_SERVER, get_info=ALL) 
    bind_dn = 'cn={0}, ou=Prod, ou=Extern, ou=User, ou=ABC, dc=DEF, dc=com'.format(username)
    # Define the Connection  
    conn = Connection(server, bind_dn, password, auto_bind=True) # Use raise_exceptions=True for exceptions 
    print ("search: {0}",format(conn.search))
    print ("conn: {0}",format(conn))
    conn.start_tls() #Session now on a secure channel. See output from following print statement and "tls started"
    print ("conn_tls: {0}",format(conn))
    d = conn.extend.standard.who_am_i() 
    print (d)
    #print ("Server Info: {0}",format(server.info))
    conn.open()
    conn.bind()

    # The LDAP search base for looking up users.
    LDAP_AUTH_SEARCH_BASE = "ou=ABC, dc=DEF, dc=com"

    if conn.bind():
        conn.search(
                 search_base=LDAP_AUTH_SEARCH_BASE,
                 search_filter= '(cn={})'.format(searchFilter), # This is the user being searched for
                 search_scope=SUBTREE # BASE & LEVEL also possible settings
                    ) 
        entry = conn.entries[0] 
        res = conn.bind()       
    print (res)

return render(request, 'search_page.html', {'entry':entry})

我的网页上收到的错误讯息:

MultiValueDictKeyError at /login_ldap/
"'username'"
Request Method: GET
Request URL:    http://127.0.0.1:8000/login_ldap/
Django Version: 1.11
Exception Type: MultiValueDictKeyError
Exception Value:    
"'username'"

我认为这与GET有关,而不再是POST方法。为什么在实现时request.method会自动设置为GET而不是POST 在Django?此类是否在views.py文件中的正确位置进行身份验证,还是应该有单独的文件? 完全包含在settings.py中的内容(与BACKEND_AUTH相关)?

编辑:

views.py 

def login_view(request): 
if request.POST: 
username = request.POST['username'] 
print ("U:{0}".format(username)) 
password = request.POST['password'] 
print ("P:{0}".format(password)) 
user = authenticate(username=username, password=password) 
print (user) 
if user is not None: 
if user.is_active: 
login(request, user) 
return redirect('index') 
else: 
messages.error(request, "User is not active in Database") 
else: 
print ("Please check your credentials!") 
messages.error(request, "Please check your username and password!") 
return render(request, 'login.html') 


index.html 

<div class="row"> 
<div class="col-lg-3"></div> 
<div class="col-lg-6"><H1>This is the public page, Please <a href="{% url 'login_ldap' %}">Login</a></H1></div> 
</div> 


urls.py 

urlpatterns = [ 
url(r'^admin/', admin.site.urls), 
url(r'^login_ldap/$', login_ldap, name='login_ldap'), 
url(r'^login/$', login_view, name='login'), 
url(r'^logout/$', logout_view, name='logout'), 
url(r'^change_password/$', change_password, name='change_password'), 
url(r'^$', index, name='index'), 
] 

settings.py 

AUTHENTICATION_BACKENDS = ( 
'django.contrib.auth.backends.ModelBackend', 
)

search_page.html

{% load static %} 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
<link href='{% static "login.css" %}' rel="stylesheet"> 

<div class="wrapper"> 
<form method='post' action="" class="form-signin">{% csrf_token %} 
<h2 class="form-signin-heading">Please login</h2> 
<input type="text" class="form-control" name="username" placeholder="Username" required="" autofocus=""/> 
<br> 
<input type="password" class="form-control" name="password" placeholder="Password" required=""/> 
<br> 
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button> 
</form> 
</div>

1 个答案:

答案 0 :(得分:0)

您可以使用get()函数来获取数据。

if request.method == "GET":
    print ("if statement executed")
    username = request.GET.get('username')

有关详细参考,请参阅此处,

MultiValueDictKeyError in Django

关于POST方法,您可能需要导入csr_exempt并在查看之前使用装饰器。

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def myView(request):