How to send a reset password email in Django on User creation?

I want to be able to let an admin create user accounts and then, instead of setting up a password for the user, the user would automatically receive a reset password email.

The view for the user creation, which also includes a Member model, is the following:

def newmember(request):

    if request.method == 'POST':
        nu_form = NewUser(request.POST)
        nm_form = NewMember(request.POST)
    
        if nu_form.is_valid() and nm_form.is_valid():
            nusave = nu_form.save()
            nmsave = nm_form.save(commit = False)
            nmsave.user = nusave
            nmsave.save()
            return redirect(members)
        else:
            print(nu_form.errors)
            print(nm_form.errors)
    
    else:

        nu_form = NewUser()
        nm_form = NewMember()

    context = {
        'nu_form': nu_form, 
        'nm_form': nm_form}
    
    return render(request, 'web/newmember.html', context)

How can I make so that upon creation of a new user, Django automatically sends an email to that new user requestion a password reset?

2 answers

  • answered 2021-10-12 17:00 user16350436

    In your models.py:

    def save(self, *args, **kwargs):
        send_mail('subject', 'message', 'your email', 'user email')
        return super().save(*args, **kwargs)
    

  • answered 2021-10-12 17:05 Shreeyansh Jain

    In order to send an email on user creation you need to define a method which shoot an email like below :-

    1. Create a text file name such as 'email_content.txt'

      Please reset password for your profile {{username}}

      Click Here
    2. Update the newmember method and add below code into it :-

               template = get_template('email_content.txt')
               context = {"usename": nmsave.user.username}
               content = template.render(context)
      
               email = EmailMessage(
                   "Congratulation, please reset your account password", content, 'App Name' <sender_email>
               )
               email.content_subtype = "html"
               email.send()
      

    add above code in try catch block

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum