I have the following function manages adding a new employee to the selected workshop,
def add_employee(request, shop_number):
workshop = get_object_or_404(Workshop, shop_number=shop_number)
context = {"workshop": workshop}
if request.method == "POST":
form = ProfileForm(request.POST, files=request.FILES)
if form.is_valid():
employee = form.save(commit=False)
employee.added_by = request.user
# Create the user associated with the employee with an unusable password
employee_user = get_user_model().objects.create_user(
username=request.POST['email'],
email=request.POST['email'],
password=None, # No password is set
first_name=request.POST['first_name'],
last_name=request.POST['last_name']
)
employee_user.set_unusable_password()
employee_user.save()
employee.user = employee_user
employee.save()
# Add the new employee to the workshop's employees
workshop.employees.add(employee)
# Conditionally add the employee to groups based on their role
if employee.is_craftman:
group, created = Group.objects.get_or_create(name='craftmen')
group.user_set.add(employee_user)
elif employee.is_salesman:
group, created = Group.objects.get_or_create(name='salesmen')
group.user_set.add(employee_user)
# Send a password reset email to the user
form = PasswordResetForm({'email': employee_user.email})
print(employee_user.email)
if form.is_valid():
request.current_site = get_current_site(request)
form.save(
request=request,
use_https=request.is_secure(),
email_template_name='registration/password_reset_email.html',
subject_template_name='registration/password_reset_subject.txt',
from_email=settings.EMAIL_HOST_USER,
)
else:
print(form.errors)
print(form)
messages.success(request, f"You have successfully added {\
employee}")
return redirect('manage_employees', shop_number=shop_number)
else:
context['form'] = form
else:
context['form'] = ProfileForm()
return render(request, 'employees/employees_form.html', context)
The code correctly prints the employee user's email, but the user does not receive the password reset email. Other parts of the code send emails successfully, but this section and the default password reset view both fail to deliver emails. I have confirmed that the specific email exists in the database. Could anyone help identify potential issues preventing the reset email from being delivered?
I figured it out. The get_users method in the PasswordResetForm also filters out users with an unusable password, so those users don’t get emails either. You’ll have to either assign some type of password to those users, or override that method in the form to not filter out by that condition.