How to create a user with Abstractbaseuser or Abstractuser. (Login errors)

Asked

Viewed 671 times

1

I’m trying to use my class Pessoa as a user in models.py. Meanwhile I tried to use AbstractUser and AbstractBaseUser. Both return me errors in the part where I try to log in, I tried several ways until I realized that I need help from someone with more experience and knowledge that I.

Man py.models:

    from django.contrib.auth.models import AbstractUser
from django.db import models

class Pessoa(AbstractUser):
    id_pessoa = models.AutoField(primary_key=True)
    cnpj = models.CharField(max_length=14, unique=True)
    nome = models.CharField(max_length=70)
    email = models.CharField(max_length=100, blank=True, null=True)
    senha = models.CharField(max_length=40, null=False)
    ativo = models.BooleanField(blank=True, null=True)
    datacadastro = models.DateField(blank=True, null=True)
    cidade = models.CharField(max_length=50, blank=True, null=True)
    uf = models.CharField(max_length=2, blank=True, null=True)
    USERNAME_FIELD = 'cnpj'

    class Meta:
        managed = False
        db_table = 'pessoa'

Detail: I am unable to remove or add fields in any model I’m using because I used inespectdb for create the models based on the database I’m using(The even though it’s already full of data). Any change, with exceptions of basic change, is out of the question.

Below my views.py with the def validates the login and redirects to the dashboard.

def dash_login(request):
    form = LoginForm(request.POST, None)
    if request.method == 'POST':
        #if form.is_valid():
        username = form.data['cnpj']
        password = form.data['senha']
        user = authenticate(username=username)
        print(username)
        #p = Pessoa.objects.filter(cnpj=form.data['cnpj']).values('id_pessoa')[0]['id_pessoa']
        #login(request, user)
        print(request.user.is_authenticated)
        #return render(request, 'dashboard.html')
    return render(request, 'login.html', {'form': form})

I use print() to test the commands before exiting by running, at the moment when it arrives at the line:

user = authenticate(username=username)

He makes this mistake:

File "C: Users Pichau Appdata Local Programs Python Python37 lib site-Packages Django db backends utils.py", line 85, in _execute Return self.cursor.execute(sql, params) Django.db.utils.Programmingerror: column pessoa.password does not exist LINE 1: SELECT "person"." password", "person"." last_login", "person"....

Regardless of whether I put password inside the authenticate the mistake is shot.

That was the second option:

def dash_login(request):
    form = LoginForm(request.POST, None)
    if request.method == 'POST':
        print(form.is_valid())
        if form.is_valid():
            cnpj = form.data['cnpj']
            print('Valido')
            print(cnpj)
            p = Pessoa.objects.filter(cnpj=cnpj).values('id_pessoa')[0]['id_pessoa']
            #print(p)
            #return redirect('dashboard', p)
    return render(request, 'login.html', {'form': form})

Where I fall into the same mistake, in case I withdraw the p and use return render(request, 'dashboard.html') I am redirecting without user id, which causes me problems to get data from it inside Dashboard.

However I still have the main problem, this table is logging in the Django login and not the login I created inside the models.py|forms.py

Error: inserir a descrição da imagem aqui

Edit1: models.py I’m trying to integrate.

from django.contrib.auth.models import AbstractUser, User
from django.db import models
from django.conf import settings


class Pessoa(AbstractUser):
    id_pessoa = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
    cnpj = models.CharField(max_length=14, unique=True)
    nome = models.CharField(max_length=70)
    email = models.CharField(max_length=100, blank=True, null=True)
    senha = models.CharField(max_length=40, null=False)
    ativo = models.BooleanField(blank=True, null=True)
    datacadastro = models.DateField(blank=True, null=True)
    cidade = models.CharField(max_length=50, blank=True, null=True)
    uf = models.CharField(max_length=2, blank=True, null=True)

    USERNAME_FIELD = 'cnpj'
    REQUIRED_FIELDS = []

    class Meta:
        managed = False
        db_table = 'pessoa'

    def __str__(self):
        return self.nome

Error message when giving migrate:

 File "C:\Users\Pichau\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY"
LINE 6:                     FROM unnest(c.conkey) WITH ORDINALITY co...

Complete error https://i.stack.Imgur.com/vV54h.png

The fact that I can’t give migrate explains the previous error that explains that the component does not exist in the table of model.

Edit: The error was generated when running inspectdb and the bank was with an outdated version(Postgresql), it was necessary to update for a newer version and run the code again, to be able inspect your bank and create templates from it.

Another possible mistake is that it prevents you from giving migrate for that same error, and this can cause field fouling errors in the database by cannot give migrate

  • After creating the new model Pessoa you spun the python manage.py makemigrations and then the python manage.py migrate?

  • Yes, I’ve even created a test backup, and I’ve tested several coiass, I don’t know where I’m going wrong. Even things work, IF, I don’t try to pull some information from Person.Bjects

  • 1

    I would guess then that you would not have added your app Django where the model Pessoa is set there in the INSTALLED_APPS of settings.py. This error that appears is exactly why Django is trying to use a table in the database that does not yet exist.

  • @It’s already there. Actually I’m having an error in giving migrate, which prevents me from creating the table via Django so that the field can exist.

  • 1

    Put this information in the question too, along with the complete error message.

1 answer

1


Ola, Try to do makemigrations and migrate placing the name of the APP

python manage.py makemigrations NOMEDOAPLICATIVO
python manage.py migrate NOMEDOAPLICATIVO

This could be the ERROR, it is not migrating properly.

I was looking at your codes and I can’t get what you’re importing (which libraries) import

An Example I’m using in my system model.py:

from __future__ import unicode_literals
import re

from django.db import models
from django.core import validators
from django.utils import timezone
from django.core.mail import send_mail
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.conf import settings


class UserManager(BaseUserManager):
  #codigo omitido para dimimuir o exemplo, ele será chamado no meio do User para gerenciar o User

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    username = models.CharField(_('username'), max_length=15,
    help_text=_(É obrigatório. 15 caracters ou menos. Letras,numeros e@/./+/-/_ caracters'),
    validators=[validators.RegexValidator(re.compile('^[\w.@+-]+$'),
     _('Use um nome Valido.'), _('invalid'))])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    birth_date = models.CharField(_('birth date'),max_length=10,null=True, blank=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
      help_text=_('Designates whether the user can log into this admin site.'))
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    avatar = models.ImageField(default='accounts/defaults/default1.jpg', upload_to=upload_location1) #, blank=True) # null=True)
    picresume = models.ImageField( default='accounts/defaults/default1.jpg', upload_to=upload_location2 ) #, blank=True , null=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username','birth_date'] 

    class Meta:
    #explica para o django se usa o plural
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        #Returna nome e sobrenome juntos 
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        #Returna nome curto.
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        #envia email , vai precisar no futuro , para resetar a senha.
        send_mail(subject, message, from_email, [self.email], **kwargs)

TIP: Use in the settings.py

LANGUAGE_CODE = 'pt-BR'

ALMOST all default words like email,user are in the interface (site) error message , help text (help text) will be in English.

login methods link 1: https://medium.com/@gabrielfgularte/custom-user-model-no-Django-d9bdf2838bd8

4 login methods link 2:(in English) https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

I hope it helped. Hug.

  • Hello, thank you very much for your explanatory reply, however I have already stopped these same links and others, I was losing myself inside an error that I believe I have already solved, but I will explain it to general understanding. Basically I use a Postgresql database, and the same was in version 9.3, so I performed it once to 0 10.6 to use inspectdb and use as models.py, since I don’t need to register data from scratch, just use it or insert a few data. And then I had errors of non-existent components, because when giving migrate it gave version errors of Postgre, soon I had to update everything and give migrate.

  • 1

    I thank you VERY much for the help, and I will check my code again for conscience-raising, I ended up using Onetoonefield, but in a future project I will use Abstractbaseuser as you used example. Until then you were the only help I had after a whole week going after help on this subject and until then no one had given me even a north. So I’m going to give a lot of value to this answer! I’m grateful!

Browser other questions tagged

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