2016-12-31 59 views
2

我想要一種方法來檢查是否有人用django填寫了他們的個人資料信息(新用戶)。如果他們不想展示一種在所有信息填寫完畢之前都不會消失的模式。無論他們進入哪個頁面,它都應該顯示此模式直到填寫完畢。確定新網站用戶的最佳方法 - Django

我應該使用javascript(ajax)來檢查一個路線,該路線將使檢查並返回一個帶有答案的json請求?如果json對象說他們是新的,我會動態地將模態附加到屏幕上。

更新:我使用django的身份驗證系統。這裏是一個登錄的例子。該檢查將是類似的,但我將使用另一個擴展了Django基本用戶類的應用程序中創建的模型。我稱之爲user_profile。我可能會檢查是否設置了用戶的名字。如果不是,我會想執行檢查。

def auth_login(request): 
    if request.POST: 

     username = request.POST['username'] 
     password = request.POST['password'] 
     user = authenticate(username=username, password=password) 

     if user: 
     # the password verified for the user 
      if user.is_active: 
       print("User is valid, active and authenticated") 
       request.session['id'] = user.id 
       request.session['email'] = user.email 
       login(request, user) 
       data = {} 
       data['status'] = "login" 
       return HttpResponse(json.dumps(data), content_type="application/json") 
       #redirect 
      else: 
       print("The password is valid, but the account has been disabled!") 
     else: 
      # the authentication system was unable to verify the username and password 
      print("The username and password were incorrect.") 
      data = {} 
      data['status'] = "The username and password are incorrect" 
      return HttpResponse(json.dumps(data), content_type="application/json") 

    return HttpResponse("hello") 
+1

有這樣做的許多方面。你可以提供更多的上下文來縮小答案的範圍。你有一個認證系統,即你可以檢查'request.user.is_authenticated()'嗎? – YPCrumble

+0

也許提供你的視圖代碼,因爲這是最有可能發生這種檢查的地方。 – YPCrumble

+0

@YPCrumble我用一個例子更新了這個問題。是的,我使用Django的身份驗證系統。 –

回答

3

一種選擇是把一個模型的方法對你user_profile的模型:

class UserProfile(models.Model): 
    name = CharField... 
    ...other fields... 

    def get_is_new(self): 
     if self.name is None: # You could include other checks as well 
      return True 
     return False 

然後,你可以檢查你的觀點,像這樣:

def auth_login(request): 
    if request.POST: 

     username = request.POST['username'] 
     password = request.POST['password'] 
     user = authenticate(username=username, password=password) 

     if user: 
     # the password verified for the user 
      if user.is_active: 
       print("User is valid, active and authenticated") 
       if user.get_is_new() is True: 
        # Return the modal 
       request.session['id'] = user.id 
       .......rest of your code.......... 
+0

我不認爲這是一個非常好的或優雅的解決方案,尤其是因爲提問的人在整個網站的每一頁上都需要這樣的解決方案。您提供的此解決方案必須在所有頁面上實施。 –

+0

@MarcusLind在下面看到我的回覆 - 如果用戶沒有提供所需的數據,則不會登錄用戶,因此這是唯一需要調用代碼的地方。 – YPCrumble

0

的最好方式是創建一個自定義上下文處理器,用於檢查當前用戶的註冊數據,並在context中設置一個布爾值,該值可在每個模板和視圖中訪問。它可以避免必須一遍又一遍地在所有視圖上調用代碼。

你可以閱讀上下文處理器在這裏: https://docs.djangoproject.com/en/1.10/ref/templates/api/

+0

我喜歡你的想法,但這只是意味着在每個模板中反覆檢查布爾值。認證系統意味着只有一個地方可以調用代碼 - 當用戶嘗試登錄時。如果他們沒有通過測試,他們不會登錄;他們必須提供更多的數據。我認爲另一種實現你要找的東西的方法是定製中間件,但缺點是你必須指定任何不需要保護的頁面。 – YPCrumble

相關問題