2014-01-08 53 views
0

我有一個非常小的Django應用程序,主要是爲了學習的目的。我正在使用由Django提供的內置用戶模型。爲了學習功能,我創建了一些頁面,這些頁面允許我創建和編輯用戶,而無需轉到管理面板。檢查密碼有效性(Django/Python)

註冊頁面允許我很容易地檢查密碼和電子郵件有效性等內容,因爲當我POST到視圖時,我只需使用user_form.is_valid()來檢查字段是否正確(用戶名少於30個字符,密碼小於128,其他條件...)。

對於我的編輯頁面,我希望使內容更具響應性,因此我通過JQuery使用了AJAX請求,從而允許我在不重新加載頁面的情況下執行操作。這個偉大的工程,但它確實讓我檢查有效性的問題,因爲我不發送的形式,我只是用JavaScript來挑出來的查詢,並在AJAX請求這樣給他們:

$.get('/dms/edit_user_changeuser/', {inputNameSend : $("#inputname").val(), usernameToSend : $("#usernameID").val(), emailToSend : $("#emailID").val(),passwordToSend : $("#passwordID").val(), disabledToSend : checkedVal}, function(data){ 
      if(data != "success"){ 
       $("#errorDisplay").show(); 
      }else{ 
       $("#savedDisplay").show(); 
       $("#user_form").hide(); 
      } 
}); 

這是關聯的視圖如何處理它:

@login_required 
def user_edit_changeuser(request): 
    # Like before, get the request's context. 
    context = RequestContext(request) 

    inputname = request.GET['inputNameSend'] 
    newUsername = request.GET['usernameToSend'] 
    newEmail = request.GET['emailToSend'] 
    newPassword = request.GET['passwordToSend'] 
    if(request.GET['disabledToSend'] == "true"): 
     disabledBool = False 
    else: 
     disabledBool = True 
    try: 
     user_obj = User.objects.get(username=inputname) 
     print("retUser") 
     user_obj.username = newUsername 
     user_obj.email = newEmail 
     user_obj.is_active = disabledBool 
     user_obj.set_password(newPassword) 
     user_obj.save() 
     print(str(disabledBool)) 
     return HttpResponse("success") 
    except Exception, e: 
     return HttpResponse(str(e)) 

這一切工作假設輸入是有效的,但有什麼樣User.checkValidPassword(newPassword)手動檢查的有效性?

+0

https://docs.djangoproject.com/en/1.3/topics/auth/#manually-checking-a-user-s-password – dm03514

回答

1

User情況下,有一個方法check_password這不正是你想要它做

user = User.object.get(username=inputname) 
user.checK_password('a_password') 

上述檢查是否當前用戶的密碼相匹配的內容會保存在數據庫中的內容。如果您是在詢問有關驗證以確保newPassword有效,即。是適當的長度,包含數字,等等。沒有理由,你不能用一個表格來驗證用戶的輸入,就像你如果不是一個基於AJAX視圖


一個側面說明,它在Python中捕獲所有異常並不是最好的。它可以掩蓋你想看到失敗的各種錯誤!

如果您希望用戶可能不存在,請明確地進行操作。

try: 
    user = User.object.get(username=inputname) 
except User.DoesNotExist: 
    # all other expections will not be caught! 
+1

真棒,這麼簡單,我幾乎得到它的權利與我的猜測在問題的最後。絕對是一個RTFM的例子,但是我的大腦被炸了,無論如何,謝謝你的幫助! :) –