【问题标题】:Django-invitations, Django-Allauth: pass model field data from custom invitation to (custom) user objectDjango-invitations,Django-Allauth:将模型字段数据从自定义邀请传递到(自定义)用户对象
【发布时间】:2020-06-14 12:29:00
【问题描述】:

我将 django-invitations 与 django-allauth 结合起来进行用户邀请和注册。

我希望管理员(通过 Django 管理员创建邀请时)提供额外数据(这里是 Patient 对象的外键)。这是通过向(自定义)邀请模型添加一个额外的字段来实现的:

class PatientInvitation (AbstractBaseInvitation):                                                                                                                                                                    
    email = models.EmailField(unique=True, verbose_name=_('e-mail address'),                                                                                                                                         
                              max_length=app_settings.EMAIL_MAX_LENGTH)                                                                                                                                              
    created = models.DateTimeField(verbose_name=_('created'),                                                                                                                                                        
                                   default=timezone.now)                                                                                                                                                                                                                                                                                                                       
    patient = models.ForeignKey(Patient, blank=True, null=True, on_delete=models.CASCADE)                                                                                                                            

    @classmethod                                                                                                                                                                                                     
    def create(cls, email, inviter=None, patient=None,  **kwargs):                                                                                                                                                   
        key = get_random_string(64).lower()                                                                                                                                                                          
        instance = cls._default_manager.create(                                                                                                                                                                      
            email=email,                                                                                                                                                                                             
            key=key,                                                                                                                                                                                                 
            inviter=inviter,                                                                                                                                                                                         
            patient=patient,                                                                                                                                                                                         
            **kwargs)                                                                                                                                                                                                
        return instance                                                                                                                                                                                              

    def key_expired(self):                                                                                                                                                                                           
        expiration_date = (                                                                                                                                                                                          
            self.sent + datetime.timedelta(                                                                                                                                                                          
                days=app_settings.INVITATION_EXPIRY))                                                                                                                                                                
        return expiration_date <= timezone.now()                                                                                                                                                                     

    def send_invitation(self, request, **kwargs):                                                                                                                                                                    
        current_site = kwargs.pop('site', Site.objects.get_current())                                                                                                                                                
        invite_url = reverse('invitations:accept-invite',                                                                                                                                                            
                             args=[self.key])                                                                                                                                                                        
        invite_url = request.build_absolute_uri(invite_url)                                                                                                                                                          
        ctx = kwargs                                                                                                                                                                                                 
        ctx.update({                                                                                                                                                                                                 
            'invite_url': invite_url,                                                                                                                                                                                
            'site_name': current_site.name,                                                                                                                                                                          
            'email': self.email,                                                                                                                                                                                     
            'key': self.key,                                                                                                                                                                                         
            'inviter': self.inviter,                                                                                                                                                                                 
        })                                                                     

当受邀用户注册时,我希望这些数据最终出现在自定义用户模型中:

class customUser(AbstractUser):                                                                                                                                                                                      
    username_validator = MyValidator()                                                                                                                                                                               
    is_patient = models.BooleanField(default=False)                                                                                                                                                                  
    patient = models.ForeignKey(Patient, null=True, blank=True, on_delete=models.CASCADE)                                                                                                                              
    username = models.CharField(                                                                                                                                                                                     
        _('username'),                                                                                                                                                                                               
        max_length=150,                                                                                                                                                                                              
        unique=True,                                                                                                                                                                                                                                                                                                                                                                                                         
    )       

我查看了传递数据的信号,但找不到具体的方法。 另一种选择似乎是将外键的 PK 添加到注册表单上的隐藏字段(但这似乎不安全)。

我有点卡在这个问题上,所以如果有人能指出我正确的方向,将不胜感激:)

问候, 乔里斯

【问题讨论】:

    标签: django django-authentication django-allauth


    【解决方案1】:

    请改用allauth's signals;您将拥有更多选择,并且您仍然可以完成您想要的。

    1. 我会在你的应用目录中创建signals.py

    2. apps.py 下注册您的信号文件,如下所示:

    from django.apps import AppConfig
    
    class AccountsConfig(AppConfig):
        name = 'app_name'
    
        def ready(self): ###<-----------
            import app_name.signals ###<-----------
    
    1. 使用user_signed_up 信号向用户更新邀请数据:

    signals.py

    from allauth.account.signals import user_signed_up
    from invitations.utils import get_invitation_model
    
    def user_signed_up(request, user, **kwargs):
        try:
            Invitation = get_invitation_model() ### Get the Invitation model
            invite = Invitation.objects.get(email=user.email) ### Grab the Invitation instance
            user.patient = invite.patient ### Pass your invitation's patient to the related user
            user.save()
        except Invitation.DoesNotExist:
            print("this was probably not an invited user.")
    
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2013-09-22
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 2014-04-30
      • 2021-01-25
      相关资源
      最近更新 更多