Django RestAuth Custom password reset link

2020-07-13 13:26发布

问题:

I have tried the solutions I found for a similar question but none worked for me.

I am using an angular frontend + DRF + Django Rest Auth, for the confirmation url, I was able to override it to point to my frontend by adding a custom adapter that looks liked this,

class AccountAdapter(DefaultAccountAdapter):

    def send_mail(self, template_prefix, email, context):
        context['activate_url'] = settings.URL_FRONT + \
            'access/verify-email/' + context['key']
        msg = self.render_mail(template_prefix, email, context)
        msg.send()

with URL_FRONT = 'http://localhost:8080/app/#/' as the setting to direct the user to the client.

My problem is implementing the same thing for the password reset url. I want it to start with the URL_FRONT setting and attached the tokens just liked what I have for the confirmation. What will be the best way to go about this?

回答1:

It looks like django-rest-auth uses django.contrib.auth.forms.PasswordResetForm to handle this: https://github.com/Tivix/django-rest-auth/blob/master/rest_auth/serializers.py#L183

And according to the Django doc you can pass your own email template (note: there was a major change in Django 1.11, so make sure you use your Django version's doc). The default template is registration/password_reset_form.html. You can override this by using your own PasswordResetSerializer (extending rest_auth.serializers.PasswordResetSerializer) in the django-rest-auth configuration.

There you can override the get_email_options() method and set your own template

def get_email_options(self):
    return {
        'email_template_name': 'path/to/your/txt_template.html',
        'html_email_template_name': 'path/to/your/html_template.html',
    }

Or maybe it's simply enough to pass your URL as success_url.



回答2:

The accepted answer works, but I also used the frontend url as the site in the admin dashboard and it worked perfectly for all my urls



回答3:

Define these variable in settings.py

  URL_FRONT = 'http://localhost:8080/app/#/'
  ACCOUNT_EMAIL_CONFIRMATION_URL = URL_FRONT+ 'verify-email/{}'
  ACCOUNT_PASSWORD_RESET_CONFIRM = URL_FRONT+ 'password-reset/confirm/'