2017-08-23 65 views
3

在我的應用程序中,我使用Django Allauth。我沒有任何用戶註冊表單。管理員將通過上傳包含用戶信息的Excel文件來註冊用戶。我已經完成了所有這些,用戶通過自動生成密碼保存在用戶表中。在我上傳用戶列表並將它們保存在數據庫中後,我想向每個用戶發送重置密碼電子郵件。Django AllAuth - 如何手動發送重設密碼電子郵件?

在allauth重置密碼你首先需要去重置頁面account/password/reset/並鍵入您的電子郵件。然後發送一封電子郵件,指導您更改密碼account/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/

是否可以在應用程序內直接發送電子郵件?該網址包含一個我不知道如何生成的密鑰!或者有沒有更好的方法來做到這一點?

回答

2

這是可能的。我的解決方案實現了用戶模型post_save信號來調用Allauth密碼重置視圖,該視圖將向用戶發送電子郵件。首先要考慮的是在管理員用戶創建表單中強制用戶電子郵件地址(如解釋here)。然後使用此代碼:

from allauth.account.views import PasswordResetView 

from django.conf import settings 
from django.dispatch import receiver 
from django.http import HttpRequest 
from django.middleware.csrf import get_token 


@receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL) 
def send_reset_password_email(sender, instance, created, **kwargs): 

    if created: 

     # First create a post request to pass to the view 
     request = HttpRequest() 
     request.method = 'POST' 

     # add the absolute url to be be included in email 
     if settings.DEBUG: 
      request.META['HTTP_HOST'] = '127.0.0.1:8000' 
     else: 
      request.META['HTTP_HOST'] = 'www.mysite.com' 

     # pass the post form data 
     request.POST = { 
      'email': instance.email, 
      'csrfmiddlewaretoken': get_token(HttpRequest()) 
     } 
     PasswordResetView.as_view()(request) # email will be sent! 
+0

非常感謝。你的回答只是時間:)我已經以不乾淨的方式實現了它,但是你的解決方案非常好,並且運行良好。 –

+0

我很高興這有幫助:) – davecaputo