Error executing login() 'Anonymoususer' Object has in attribute '_meta'

Asked

Viewed 474 times

0

I’m trying to log into an account of Django to redirect to the main page of my project, but the command login returns me the following error.

AttributeError at /login/
'AnonymousUser' object has no attribute '_meta'

I am using Onetoonefield to use cnpj/password from a table in my database.

I am testing both with the Django login and password as the table and both return the same error.

py views.

def login_log(request):
    form = PessoaForm(request.POST, None)
    if request.method == 'POST':
        cnpj = form.data['cnpj']
        senha = form.data['senha']
        print(form.is_valid())
        if form.is_valid():
            user = authenticate(request, cnpj=cnpj, senha=senha)
            user2 = authenticate(request, username=cnpj, password=senha)
            print(user)
            print(user2)
            print(login(request, user))
            #return redirect('dashboard', idpessoa)
    return render(request, 'login.html', {'form': form})

idpessoa is used to send next to the url and access the user who is logging in. In my code it has the utility correctly and is working. (Just to awaken awareness that it is not the mistake)

I know the mistake is on this line

print(login(request, user))

and the print is there only for testing

In case you need me Forms.py

class PessoaForm(ModelForm):
    class Meta:
        model = User
        fields = ['cnpj', 'senha']

1 answer

1


Hello

Try to remove the request , This could be the possible mistake.

user = authenticate(cnpj=cnpj, senha=senha)

And to redirect to another page in case of success

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect

return HttpResponseRedirect(reverse('index')) 

I will give an example that I use in my system very good in the forms.py:

from django.contrib.auth import authenticate, login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate
from django.contrib import messages
from django.shortcuts import redirect

def user_login(request):
    if request.method == 'POST':
        # Pegque o dados necessarios do HTML
        email = request.POST.get('email')
        password = request.POST.get('password')

        # Use a autenficação do Django
        user = authenticate(email=email, password=password)

        # Se tem usuario
        if user:
            #Checa se usuario esta ativo, é necessario para o futuro, caso voce destive o usuario ele não ira mais logar
            if user.is_active:
                # Logando.
                login(request,user)
                # SE LOGAR,Redireciona o usuario para uma pagina , nesse caso a Index .
                return HttpResponseRedirect(reverse('index'))
            else:
                # Envia para uma pagina dizendo:
                return HttpResponse("Sua conta não esta ativa.")
        else:
                #testes
                # print("Erro no login")
                # print("email usado: {} e senha {}".format(email,password))
                #essa parte é legal , mostra para o usuario uma resposta
                messages.error(request, 'Erro no email ou senha')
#volta para pagina do login para uma nova tentativa
            return redirect('login')

        else:
            #Inicianiliza a pagina.
            return render(request, '...login.html', {})

Use in the login.html to appear the messages.error (i use bootstrap):

{% if messages %}                
                    <div class="alert alert-danger" role="alert">                    
                      {% for message in messages %}
                           <div{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</div>
                      {% endfor %}
                </div>
             {% endif %}

Embrace, And may the force be with you.

  • Thank you again for describing a complete and instructive response! I can’t test anymore because I don’t know if I can and I want to go back to that error, but I believe that if I play your code will work, and if not, there’s still another post where the other bugs are fixed.

Browser other questions tagged

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