0

I'm having problem in the built-in login function in Django.

Here is the views.py code:

def login_page(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST) 
        if form.is_valid:
            user = form.get_user()
            login(request, user)    
            return redirect('index')
    else: 
        form = AuthenticationForm() 
    return render(request, 'login.html', {'form':form})

And below is my html code.

<form action="{% url 'login' %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Log in">
</form>

As soon as I click the 'Log in' button, it gives an error that says: 'AnonymousUser' object has no attribute '_meta'

I don't see which part is wrong. I very much appreciate your help. :)

2
  • @kyore I am using a custom user model and this is the same error that pops up while serializing user object. Any tips? Commented Mar 9, 2020 at 10:58
  • @ruddra solved your problem. Commented Mar 9, 2020 at 11:12

1 Answer 1

2

is_valid is not a property, it is a function. So you need to call it like this:

if form.is_valid():

Explanation: As you are not calling that function, the AuthenticationForm is not authenticating the user inside clean method. Hence you are not getting the User instance with form.get_user() method.

Sign up to request clarification or add additional context in comments.

1 Comment

Man this really got a huge trouble off of me. Thanks a lot. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.