【问题标题】:Convert a function from many to single将一个函数从多个转换为单个
【发布时间】:2011-06-03 18:12:15
【问题描述】:

我有一个来自 django-registration 的功能,它可以将激活电子邮件重新发送给给定的收件人。我正在尝试将该功能从接受给定电子邮件的多个用户转换为每封电子邮件仅接受一个用户。但是,当我尝试更改它时,它会抛出 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 循环,该函数将无法“工作”。我这里的问题似乎是什么?谢谢。

【问题讨论】:

    标签: django django-registration


    【解决方案1】:

    尝试:

    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(email=email) 返回一个 queryset,它是从查询 filter(email=电子邮件)。原文中的 for 循环遍历这些对象中的每一个,并发送相应的电子邮件。您正在尝试调用 send_

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多