Detect distinction between the model chosen by the user for registration

Asked

Viewed 100 times

0

Hello, so, I created some models to register users in Django 2.0 and now I need to know which one the user chose to register. As you can see I have the individual model (Customusern), legal entity (Customcompany) and the admin model (Customuser), I made a template for the user to choose between these two:

<div class="row">
     <div class="col-4"></div>
     <div class="col-5">
        <h2>Como deseja se cadastrar? </h2>
     </div>
</div>
<br>
<br>
<div class="row">
    <div class="col-3"></div>
    <div class="col-2">
        <a href="{% url 'register' %}"><button type="button" class="btn btn-info btn-lg">Pessoa física   <i class="fas fa-user-alt"></i></button></a>
    </div>
    <div class="col-2"></div>
    <div class="col-2"> <a href="{% url 'registercom' %}"><button type="button" class="btn btn-info btn-lg">Pessoa jurídica   <i class="fas fa-building"></i></button>
    </div>
</div>

And that redirects to these two functions:

def register(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST or None)
        if form.is_valid():
            user = form.save()
            user.set_password(user.password)
            form.save()
            return render(request, 'register-sucess.html', {'user': user})
    else:
        form = CustomUserCreationForm()
    return render(request, 'register.html', {'form': form})

def registercom(request):
    form = CustomCompanyCreationForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        user.set_password(user.password)
        form.save()
        return render(request, 'register-sucess.html', {'user': user})
    return render(request, 'register.html', {'form': form})

How do I create an algorithm that I can detect this difference, being that they are different models, for example so that I can perform different profile edits with the appropriate fields?

#TODO: MODEL ADMIN E PAI DOS DEMAIS MODELS DE LOGIN
class CustomUser(AbstractBaseUser):
    email = models.EmailField(_('E-mail '), max_length=255, unique=True)
    username = models.CharField(_('Nome de usuário '), max_length=15, unique=True)
    date_joined = models.CharField(_('Data de início '), max_length=20, default=timezone.now())
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()
    class Meta:
        verbose_name = _('Usuário')
        verbose_name_plural = _('Usuários')
    def __str__(self):
        return self.username
    def has_perm(self, perm, obj=None):
        return True
    def has_module_perms(self, app_label):
        return True
    @property
    def is_staff(self):
        return self.is_admin

#TODO: MODEL DE PESSOA JURÍDICA, SEM VALIDADOR PARA CPNPJ/TELEFONE/CEP
class CustomCompany(CustomUser):
    name = models.CharField(_('Razão social '), max_length= 30, default=' ')
    UF_CHOICES = (
        ('ac','AC'),
        ('al','AL'),
        ('ap','AP'),
        ('am','AM'),
        ('ba','BA'),
        ('ce','CE'),
        ('df','DF'),
        ('es','ES'),
        ('go','GO'),
        ('ma','MA'),
        ('mt','MT'),
        ('ms','MS'),
        ('mg','MG'),
        ('pa','PA'),
        ('pb','PB'),
        ('pr','PR'),
        ('pe','PE'),
        ('pi','PI'),
        ('rj','RJ'),
        ('rn','RN'),
        ('rs','RS'),
        ('ro','RO'),
        ('rr','RR'),
        ('sc','SC'),
        ('sp','SP'),
        ('se','SE'),
        ('to','TO'),

    )
    DEP_CHOICES = (
        ('lab', 'Laboratório Protético'),
        ('clin', 'Clínica Odontológica'),
        ('out', 'Outro tipo'),
    )
    departamento = models.CharField(_('Estabelecimento '), max_length=10, choices=DEP_CHOICES, default='clin')
    cnpj = models.CharField(_('CNPJ(somente números) '), max_length=12, unique=True, default=' ')
    telefone = models.CharField(_('Telefone '), max_length=12, default=' ')
    cep = models.CharField(_('CEP '), max_length=10, default=' ')
    endereco = models.CharField(_('Endereço '), max_length=30, default=' ')
    cidade = models.CharField(_('Cidade '), max_length=20, default=' ')
    uf = models.CharField(_('UF '), max_length=2, choices=UF_CHOICES, default='sp')
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'departamento', 'cnpj', 'telefone', 'cep', 'endereco', 'cidade', 'uf']
    class Meta:
        verbose_name = 'Cadastro jurídico'
        verbose_name_plural = "Cadastros jurídicos"

    def create_user(sender, instance, created, **kwargs):
        if created:
            CustomCompany.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user(sender, instance, **kwargs):
        instance.profile.save()

#TODO: MODEL DE PESSOA FÍSICA, SEM VALIDADOR PARA CPF/TELEFONE/CEP
class CustomUserN(CustomUser):
    name = models.CharField(_('Nome completo '), max_length=30, default=' ')
    USER_CHOICES = (
        ('dentista', 'Dentista'),
        ('protetico', 'Protético'),
        ('outra','Outra'),
    )
    UF_CHOICES = (
        ('ac', 'AC'),
        ('al', 'AL'),
        ('ap', 'AP'),
        ('am', 'AM'),
        ('ba', 'BA'),
        ('ce', 'CE'),
        ('df', 'DF'),
        ('es', 'ES'),
        ('go', 'GO'),
        ('ma', 'MA'),
        ('mt', 'MT'),
        ('ms', 'MS'),
        ('mg', 'MG'),
        ('pa', 'PA'),
        ('pb', 'PB'),
        ('pr', 'PR'),
        ('pe', 'PE'),
        ('pi', 'PI'),
        ('rj', 'RJ'),
        ('rn', 'RN'),
        ('rs', 'RS'),
        ('ro', 'RO'),
        ('rr', 'RR'),
        ('sc', 'SC'),
        ('sp', 'SP'),
        ('se', 'SE'),
        ('to', 'TO'),

    )
    tipo = models.CharField(_('Profissão '), max_length=10, choices=USER_CHOICES, default='dentista')
    cpf = models.CharField(_('CPF(somente números) '), max_length=12, unique=True, default=' ')
    cro = models.CharField(_('CRO(somente números) '), max_length=25, unique=True, default=' ')
    Empresa_para_qual_trabalha = models.ForeignKey(
        CustomCompany, on_delete=models.CASCADE, null=True, blank=True
    )
    telefone = models.CharField(_('Telefone '), max_length=12, default=' ')
    foto = models.ImageField(upload_to='fotos_usuarios', null=True, blank=True)
    cep = models.CharField(_('CEP '), max_length=10, default=' ')
    endereco = models.CharField(_('Endereço '), max_length=30, default=' ')
    cidade = models.CharField(_('Cidade '), max_length=20, default=' ')
    uf = models.CharField(_('UF '), max_length=2, choices=UF_CHOICES, default='sp')
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'tipo', 'cpf', 'cro', 'Empresa_para_qual_trabalha', 'telefone','foto', 'cep', 'endereco', 'cidade', 'uf']
    class Meta:
        verbose_name = 'Cadastro físico'
        verbose_name_plural = "Cadastros físicos"

    def create_user(sender, instance, created, **kwargs):
        if created:
            CustomUserN.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user(sender, instance, **kwargs):
        instance.profile.save()
  • I didn’t understand your question. But looking at your model, the correct thing is to create a model Pessoa with information that is equal in physics and juridical, and other two models PessoaFisica(Pessoa) and PessoaJuridica(Pessoa) inheriting the information of Pessoa.

  • I did this, being Customuser for admin registration, inheriting from him Customusern for physics and Customcompany for legal, I did not add the common data because it hinders the registration of the superuser that would be the parent model of the other two. But what I meant was that each model is directed according to the option given by the user through Buttons, but I need to detect which of these was chosen by the user, I thought to save a variable with a numbering indicating which type of model was saved, but I’m not sure where to put it and how to do it. Have any tips?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.