I have a CustomUser model, working fine . It stores a value in otp table everytime on save instance. but i want to send this pre saved otp value through email . email function is working good but i don't how to make query here for that specific user who wants get the otp. as every user would have a random value.
here is the code. #models.py
class CustomUser(AbstractUser):
username = None
phone_regex = RegexValidator(
regex=r'^\ ?1?\d{9,14}$', message="Phone number must be entered in the form of 129999999999.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, unique=True,
verbose_name='Phone Number', blank=False)
email = models.EmailField(_('email address'), unique=True)
isPhoneVerified = models.BooleanField(
verbose_name='Is Phone Number Verified?', default=False)
isEmailVerified = models.BooleanField(
verbose_name='Is Email Verified?', default=False)
otp = models.CharField(max_length=6)
USERNAME_FIELD = 'phone_number'
REQUIRED_FIELDS = ['email']
objects = CustomUserManager()
def __str__(self):
return self.phone_number " | " self.email
# Method to Put a Random OTP in the CustomerUser table to get verified for the next time after save.
def save(self, *args, **kwargs):
number_list = [x for x in range(10)] # list comprehension
code_items = []
for i in range(6):
num = random.choice(number_list)
code_items.append(num)
code_string = "".join(str(item)
for item in code_items) # list comprehension again
# A six digit random number from the list will be saved in otp table
self.otp = code_string
super().save(*args, **kwargs)
send_otp functions
@receiver(post_save, sender=CustomUser)
def send_otp(sender, instance, created, **kwargs):
if created:
try:
subject = "Your email needs to be verified"
message = f'Hi, use this following OTP to Get verified your email : OTP({""})/' #here i want to put the otp table value for the user who is making the request.
email_from = settings.EMAIL_HOST_USER
recipient_list = [instance.email]
send_mail(subject, message, email_from, recipient_list)
except Exception as e:
print(e)
I hv gone throu django docs but im unable to get an idea how we will filter the exact user who is making the request. help will be appreciated. thanks.
CodePudding user response:
The solution is in your send_otp function.
recipient_list = [instance.email]
Use the same approach as you selected the email, the same way you can select OTP.
Correct Code:
@receiver(post_save, sender=CustomUser)
def send_otp(sender, instance, created, **kwargs):
if created:
try:
subject = "Your email needs to be verified"
message = f'Hi, use this following OTP to Get verified your email : OTP({instance.otp})/' #here i want to put the otp table value for the user who is making the request.
email_from = settings.EMAIL_HOST_USER
recipient_list = [instance.email]
send_mail(subject, message, email_from, recipient_list)
except Exception as e:
print(e)
