Django AllAuth - How to manually send a reset-password email?

后端 未结 2 1010
长发绾君心
长发绾君心 2020-12-19 05:36

In my application I am using Django Allauth. I don\'t have any registration form for users. The admin is going to register users by uploading an excel file that contains use

相关标签:
2条回答
  • 2020-12-19 05:59

    It's possible. My solution implements a User model post_save signal to call the Allauth Password reset view which will send the user the email. The first thing to consider is to make the user email address mandatory in the admin user create form (as explained here). And then use this code:

    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)
  • 2020-12-19 06:03

    You can try to get URL for specific user using something like this:

    from allauth.account.forms import EmailAwarePasswordResetTokenGenerator
    from allauth.account.utils import user_pk_to_url_str
    
    token_generator = EmailAwarePasswordResetTokenGenerator()
    user = User.objects.get(email='example@example.com')
    temp_key = token_generator.make_token(user)
    path = reverse("account_reset_password_from_key", 
                   kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key))
    
    0 讨论(0)
提交回复
热议问题