Dania
Dania

Reputation: 41

How to send emails with Django for Password Reset?

I am trying to send password change link to an email address which a user will type. I typed my email but it is not sending me any link. How to resolve this issue?

urls

urlpatterns = [
    path('password_reset/',auth_views.PasswordResetView.as_view
    (template_name='users/password_reset.html'),
     name='password_reset'),
    path('password_reset_done/',auth_views.PasswordResetDoneView.as_view
    (template_name='users/password_reset_done.html'),
     name='password_reset_done'),
    path('password_reset_confirm/',auth_views.PasswordResetConfirmView.as_view
     (template_name='users/password_reset_confirm.html'),
      name='password_reset_confirm')]

settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')

Upvotes: 1

Views: 5899

Answers (1)

Gino
Gino

Reputation: 1113

I use these as my urls. The main difference I spot with yours right away is with password-reset-confirm. Make sure your passing the token.

from django.contrib.auth import views as auth_views


path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'),
path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),
path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'),
path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),

My settings look like this

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_POST = 587
EMAIL_USE_TLS = True


EMAIL_HOST_USER = os.environ.get('traces_email')
EMAIL_HOST_PASSWORD = os.environ.get('traces_email_password')

Also please note that you need to set up a g-mail account to allow Django or any other app to access it, it doesn't work automatically. The password you receive after doing this IS NOT the same as the password you normally log in with. It may be this that is causing you issues.

As I saw you are missing the tokens in your password-reset-confirm URL it is perhaps also the problem that your don't have a token generator.

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six


class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active)
        )
account_activation_token = TokenGenerator()

I created this in a file named token_generator.py.

Upvotes: 1

Related Questions