Multiple Users and Authentication - Django

3

I'm developing a project in Django that has two types of users: Client and Accountant. Each one is authentic and has keys that identify them differently. The Client has as primary key his CNPJ. The accountant has as key the composition of his CRC, CNPJ and the Client's primary key (CNPJ). That is, we can have several counters with the same CNPJ and CRC but CNPJ (of the Client) different. The following image shows the Entity-Relational model of this "mini-world".

Myproblemis:HowtoimplementthisinDjango,sinceitallowsonlyoneuserinyourUserModel?

Myfrustratedapproachisasfollows:

  • IcreateaUserProfilethatinheritsfromAbstractBaseUserandPermissionsMixin(Iconfiguresettings.pyforthisnewuser).

  • IputalltheparametersthatarecommonbetweenClientandCounterinUserProfile.

  • Icreatetwotemplates:ClientandCounter,whichinheritfromUserProfile.

  • InthecounterImaketheForeignKeyrelationshipandIputtheattributesthatonlybelongtotheCounter-nameandcrc.

  • Myquestionis:Giventhistemplate,whatisthebestwaytoimplementthesetwotypesofuserswhoauthenticateandhavedifferentprimarykeys?

    FilesModels.py

    #!/usr/bin/python#-*-coding:utf-8-*-fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimport(AbstractBaseUser,PermissionsMixin,UserManager)classUserProfile(AbstractBaseUser,PermissionsMixin):username=models.CharField('CNPJ',max_length=20,unique=True)razao_social=models.CharField('RazãoSocial',max_length=100)telefone=models.CharField('Telefone',max_length=20,blank=True)celular=models.CharField('celular',max_length=20,blank=True)email=models.EmailField('E-mail',unique=True,max_length=255,)is_active=models.BooleanField('Estaativo?',blank=True,default=True)is_staff=models.BooleanField('Edaequipe?',blank=True,default=False)date_joined=models.DateTimeField('Datadeentrada',auto_now_add=True)objects=UserManager()USERNAME_FIELD='username'#CampoqueeunicoereferenciadahoradologinREQUIRED_FIELDS=['email']#Paracriarsuper-usuariodef__str__(self):returnself.usernamedefget_short_name(self):returnself.usernamedefget_full_name(self):returnstr(self)classMeta:verbose_name="Usuario"
            verbose_name_plural = "Usuarios"
    
    #Done
    class Cliente(UserProfile):
    
        def __str__(self):
            return self.username
    
        class Meta:
            verbose_name = "Cliente"
            verbose_name_plural = "Clientes"
    
    #Done
    class Contador(UserProfile):
    
        clientes = models.ForeignKey(Cliente, on_delete=models.CASCADE,blank = True,null=True)
    
        crc =  models.CharField('CRC',unique=True,  max_length=20)
        nome = models.CharField('Nome', blank= True, max_length=100)
    
        def __str__(self):
            return self.crc
    
        def get_short_name(self):
            return self.nome
    
        def get_full_name(self):
            return str(self)
    
        class Meta:
            unique_together = (("crc", "email"),)
            verbose_name = "Contador"
            verbose_name_plural = "Contadores"
    

    I also put pastebin.com

        
    asked by anonymous 18.06.2018 / 02:49

    1 answer

    1

    Authentication of them must be through e-mail, this being a unique attribute. So you keep the primary keys for each type of user.

    You can create a Profile class (Client or Counter) and then another UserPerfil call, in that you define which profile each user will have on your system. And when accessing areas where only the client or counter has access you check userPerfil.objects.filter(perfil='Cliente')

    class Perfil(models.CharField):
       nome = models.CharField(max_length=50)
    
    
    class UserProfile(models.Model):
       user = models.ForeignKey(User)
       profile = models.ForeignKey(Perfil, on_delete=models.CASCADE)
       active = models.BooleanField(default=True)
    

    The Client and Counter information creates two models. Remember that the primary-key of django is the id, created automatically. The primary key that you are wanting in the counter will always repeat itself breaking the rules of normalization. You just relating customer within counter can retrieve information as easy as what x client counters have, what customers the counter y has and there goes

    class Cliente(models.CharField):
        cnpj = models.CharField(max_length=10)
    
    
    class Contator(models.CharField):
        crc = models.CharField(max_length=4)
        cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)
    
        
    23.06.2018 / 18:01