I want to create a user at the creation of an object. This object is linked to the user by a foreign key. I have override the def_save() method to create the user and link it to the object.
Problem: I generate a random password for this user and I would like to send it by e-mail not to the just created user but to the user.
def save(self, *args, **kwargs):
if self._state.adding:
super(Machine, self).save(*args, **kwargs)
username = f"machine_{slugify(self.site.client.name).lower()}_{self.id}"
password = User.objects.make_random_password()
self.user = User.objects.create(
username=username,
password=password
)
self.save(update_fields=['user'])
send_mail(
f'Password of {username}',
f'Password: {password}',
settings.DEFAULT_FROM_EMAIL,
[self.request.user.email],
fail_silently=True,
)
else:
super(Machine, self).save(*args, **kwargs)
The problem is that I don't have access to self.request in this method.
How can I access to request in my def save()?
Or how can I get the password value in my view?