Saturday, April 17, 2021

Using Signals and method in models to automate key and qrcode>> help


Hello ,

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.

Please advice

Thanks

The profile model

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(Useron_delete=models.CASCADEblank=Truenull=True)

    #qr_creation = otp_google_auth(secret, user)
    otp_code = models.CharField(max_length=200default=token_creation)
    user_qr =  models.ImageField(upload_to='images/'defaultNone)
    last_name = models.CharField(max_length=200null=Trueblank=True)
    phone = models.CharField(max_length=200null=Trueblank=True)

    def __str__(self):
        return str(self.user)

    def token_creation(self):

        secret = pyotp.random_base32()
        self.otp_code.save(secretsave=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_savesender=User)
def create_profile(senderinstancecreated, **kwargs):
    
    if created:
        Profile.objects.create(user=instance)
        print('Profile created!')

#post_save.connect(create_profile, sender=User)

@receiver(post_savesender=User)
def update_profile(senderinstancecreated, **kwargs):
    
    if created == False:
        instance.profile.save()
        print('Profile updated!')


    

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/94e3236b-3633-4937-89bd-bf38adade13dn%40googlegroups.com.

No comments:

Post a Comment