2017-10-19 76 views
0

我所試圖做的是以下幾點:Django的認證用戶搜索工作不正常

1. Retrieve a User record (from the DJango authentication system) is in 
    the DB 
2. get the Username (from that record) 
3. Use the "username" to look for a record in a *different* table. 
4. If the record *is not* there (in the *different* table), then create one. 

我得到的是什麼樣子的查詢到用戶表,即使我已經中下面的錯誤views.py

from django.contrib.auth.models import User

而且,爲什麼DoesNotExist錯誤發生(當一個正在尋找在認證系統中的用戶)目前尚不清楚。爲什麼我得到這個錯誤?

TIA

這是錯誤消息 enter image description here

這是怎樣的 「應用程序」 被構造

enter image description here

views.py

from django.shortcuts import render 
from django.http import HttpResponseRedirect, HttpResponse 
from django.core.urlresolvers import reverse 
from authinduction.models import Mstrauthownerrdx 
from django.contrib.auth.models import User 

def inductowner(request): 

    username = request.POST.get('username') 
    user = User.objects.get(username=username) 

    myprofile = user.userprofileinfo 

    num_results = Mstrauthownerrdx.objects.filter(logonid=username).count() 

    if not (num_results == 0 or num_results == 1): 
     raise ValueError('Number of items found '+ num_results + ' is not valid') 

    if num_results == 0: 
     u = Mstrauthownerrdx.objects.create(logonid=username, emailaddr=user.email, 
       worktype=1, memo='OWNER', active=1, formpagelastfilled=myprofile.lastpgprocno, 
       formcomplete=myprofile.nextpgprocno, reclocktype=1, reclockid=1) 

     u.save() 

    return render(request, 'authinduction/owner/index.html') 

回答

0

你試圖讓用戶不存在。試着找出你的確切的username變量,並用admin中的數據庫檢查它。你會看到它不存在。例如,你可以做以下捕獲錯誤:

try: 
    user = User.objects.get(username=username) 
    myprofile = user.userprofileinfo 
    num_results = Mstrauthownerrdx.objects.filter(logonid=username).count() 
except User.DoesNotExist: 
    num_results = 0 
+0

感謝您的答覆。我看到我沒有獲得價值迴歸的原因是因爲這部分代碼:「username = request.POST.get('username')」返回None。 –

0

你發送一個GET請求。在您的代碼中,您嘗試從username POST參數獲取用戶名。由於視圖沒有用戶名您的觀點是試圖獲取沒有username這恐怕在你的數據庫中不存在的User對象。

要修復它,您必須將username作爲GET參數傳遞,或發送帶有username作爲參數的POST請求。