You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django内置登录函数报错:'AnonymousUser' object has no attribute '_meta'

Fixing the 'AnonymousUser' object has no attribute '_meta' Error in Django Login

Hey there, I see exactly what's causing this error! Let's break it down:

The problem is in your views.py code—you're missing parentheses when checking if the form is valid. is_valid is a method, not a property, so you need to call it with () to actually run the validation logic.

What's happening under the hood:

  • Without the parentheses, if form.is_valid just checks if the method exists (which it does), so it skips the validation entirely.
  • Then form.get_user() returns an AnonymousUser because the form never validated the credentials.
  • When you try to call login(request, user) with an AnonymousUser, Django throws that error because this user type doesn't have the _meta attribute required for the login process.

Corrected views.py code:

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

Quick check:

After fixing this, the form will properly validate the username and password. If the credentials are correct, form.get_user() will return a valid User object, and the login process will work as expected. If the credentials are wrong, the form will show the appropriate error messages instead of trying to log in an anonymous user.

内容的提问来源于stack exchange,提问作者Ryan Oh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:52:49