2011-06-03 84 views
1

我有一個django註冊函數,它將激活電子郵件重新發送給給定的收件人。我試圖將接收多個用戶的函數轉換爲每個電子郵件只有一個用戶。然而,當我嘗試改變它時,它會拋出一個AttributeError將函數從多個轉換爲單個函數

def resend_activation(self, email, site): # for multiple emails -- this works 
    sent = False 
    users = User.objects.all().filter(email=email) 

    if users: 
     for user in users: 
      registration_profiles = self.all().filter(user=user) 
      for registration_profile in registration_profiles: 
       if not registration_profile.activation_key_expired(): 
        registration_profile.send_activation_email(site) 
        sent = True 
    return sent 

def resend_activation(self, email, site): # for single email -- this does not work 
    sent = False        
    user = User.objects.all().filter(email=email) 

    if user: 
     registration_profile = self.all().get(user=user) 
     if not registration_profile.activation_key_expired(): 
      registration_profile.send_activation_email(site) 
      sent = True 
    return sent 

後者函數拋出AttributeError,但我不明白,爲什麼這個功能不「工作」沒有for循環。這裏似乎是我的問題?謝謝。

回答

4

嘗試:

def resend_activation(self, email, site): 
    sent = False 
    # Get the user you are looking for 
    try: 
     single_user = User.objects.get(email=email) 
    except User.DoesNotExist: 
     return false 

    # Get all the profiles for that single user 
    registration_profiles = self.all().filter(user=user) 
     # Loop through, and send an email to each of the profiles belonging to that user 
     for registration_profile in registration_profiles: 
      if not registration_profile.activation_key_expired(): 
       registration_profile.send_activation_email(site) 
       sent = True 
    return sent 

在原有的User.object.filter(電子郵件=電子郵件)返回一個查詢集這是從查詢過濾器所返回從數據庫對象的集合(電子郵件=電子郵件)。原始中的for循環遍歷每個對象,併發送相應的電子郵件。您正嘗試致電send_

相關問題