i
have a simple model that create additional one to one relation to User
a profile like table with tables of pytop code and qrcode associated
per user.
I had success to create the pytop code ,but the qr code i have difficulty to achieve it since i need to get,
The
current users created and the pyotp code, on evry user creation i have
signals receivers that create the additional profile associated tables ,
but i need your advice ,on methods attached to the model that will
create automatically the request tables , what is the best practice to
achieve such task.
from django.db import models
from django.contrib.auth.models import User
import pyotp
import qrcode
# Create your models here.
def otp_google_auth(code,usr):
print('details: ',code,usr)
googleauth = pyotp.totp.TOTP(code).provisioning_uri(name=str(usr) + '@google.com', issuer_name='Secure Dalet') qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(googleauth)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
google_qr = img
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
#qr_creation = otp_google_auth(secret, user)
otp_code = models.CharField(max_length=200, default=token_creation)
user_qr = models.ImageField(upload_to='images/', default= None)
last_name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return str(self.user)
def token_creation(self):
secret = pyotp.random_base32()
self.otp_code.save(secret, save=False)
super().save()
The signals for profile table
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
print('Profile created!')
#post_save.connect(create_profile, sender=User)
@receiver(post_save, sender=User)
def update_profile(sender, instance, created, **kwargs):
if created == False:
instance.profile.save()
print('Profile updated!')