Search code examples
pythondjangoformsdjango-formsdjango-authentication

django login form returns 'AnonymousUser' object has no attribute '_meta'


I am working on a django web app. In this web app, I have a login page. But when I use the click the login button, I get the following error message

'AnonymousUser' object has no attribute '_meta'

I tried looking for this online and found these links in StackOverflow. link1 and link2. But the answers provided in these links do not seem to be working for me.

This is my code so far views.py

def login_page(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        user = form.get_user()
        login(request, user)

        if form.is_valid():
            return redirect('global:homepage')

    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {'form': form})

login.html

<form class="" action="{% url 'accounts:login' %}" method="post">
    {% csrf_token %}
    {% for field in form %}
    <p>
        <div class="form-group">
            {% render_field field class="form-control" placeholder=field.label %}
            {% if field.help_text %}
            <p class="help-block"><small>{{ field.help_text }}</small></p>
            {% endif %}
        </div>

        {% for error in field.errors %}
        <p style="color: red">{{ error|add_class:'text-danger' }}</p>
        {% endfor %}
    </p>
    {% endfor %}
    <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Log in</button>
</form>

Not sure what I am doing wrong or what the error message means


Solution

  • You need to call form.is_valid() before retrieving and logging in the user as they may not have provided the correct credentials

    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('global:homepage')
        else:
            form = AuthenticationForm()
        return render(request, 'accounts/login.html', {'form': form})