Django Authenticate and Login Issue: 'AnonymousUser' object has no attribute '_meta'

I am facing the issue while authenticating the email and password with the Django built in function authenticate and login.

Below are my codes:


{% extends 'base.html' %} {% block content %}
<div class="container w-[65%] mx-auto px-4 py-8 bg-gray-200 mt-8 rounded-md">
  <h2 class="text-bold text-3xl text-center">Login Form</h2>
  <form action="" method="post">
    {% csrf_token %}
    <div class="overlap mt-5 mx-auto text-center">
    <div class="email">
        class="outline-1 rounded-md p-4 w-[80%] mb-4"
        placeholder="Enter Email"
    <div class="password">
        class="outline-1 rounded-md p-4 w-[80%] mb-4"
        placeholder="Enter Password"
    <div class="w-[80%] mx-auto">
        class="bg-indigo-500 hover:bg-indigo-600 px-8 py-4 rounded-md text-white"
        LOGIN NOW
{% endblock content %}

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignupForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    username = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Enter Username',
        'class': 'p-4 w-[80%] mx-auto mb-4 rounded-md mx-auto'

    email = forms.CharField(widget=forms.EmailInput(attrs={
        'placeholder': 'Enter Email',
        'class': 'p-4 w-[80%] mx-auto mb-4 rounded-md mx-auto'

    password1 = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Choose Password',
        'class': 'p-4 w-[80%] mx-auto mb-4 rounded-md mx-auto'

    password2 = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Repeat Password',
        'class': 'p-4 w-[80%] mx-auto mb-4 rounded-md mx-auto'

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

# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=30)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):

class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    price = models.IntegerField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to='images_hub', null=True, blank=True)
    shop = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ('created',)

    def __str__(self):

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('product/<int:pk>/', views.product, name='product'),
    path('register/', views.register, name='register'),
    path('login/', views.loginForm, name='login'),
    path('logout/', views.logoutForm, name='logout'),

from django.shortcuts import render, redirect
from .models import Category, Product
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, logout, authenticate
from .forms import SignupForm

# Create your views here.
def home(request):
    products = Product.objects.all()[:6]
    categories = Category.objects.all()
    context = {
    return render(request, 'page/home.html', context=context)

def product(request, pk):
    product = Product.objects.get(pk=pk)
    return render(request, 'page/product.html', {'product':product})

def register(request):
    form = SignupForm()

    if request.method == 'POST':
        user = SignupForm(request.POST)
        if user.is_valid():
            return redirect('home')

    return render(request, 'page/register.html', {'form': form})

def loginForm(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')

            user = User.objects.get(email=email)
            print('Something went wrong! Try again.')

        auth_login = authenticate(request, email=email, password=password)

        if user is not None:
            login(request, auth_login)
            return redirect('/')

    return render(request, 'page/login.html')

def logoutForm(request):
    return redirect('home')

Please post the complete traceback that you are receiving.

Thanks for the reply Ken.

Here is the complete traceback from VS Code:

Traceback (most recent call last):
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/venv/lib/python3.10/site-packages/django/core/handlers/", line 55, in inner
    response = get_response(request)
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/venv/lib/python3.10/site-packages/django/core/handlers/", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/website/page/", line 46, in loginForm
    login(request, auth_login)
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/venv/lib/python3.10/site-packages/django/contrib/auth/", line 138, in login
    request.session[SESSION_KEY] =
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/venv/lib/python3.10/site-packages/django/utils/", line 268, in inner
    return func(_wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute '_meta'

You’ve got a couple different things potentially wrong here.

Are you using a custom authentication backend?

If not, have you specified your USERNAME_FIELD for your custom User model?

You’re catching the exception on the User.objects.get(...), but not changing the flow of your code if an error occurs - if the get fails, it’s still going to try and authenticate, which is not what you want to have happen.

Also, you’re saving the return from authenticate in auth_login, but the next statement (the if) is checking user. Review the example at Using the Django authentication system | Django documentation | Django

Thanks for support. I think i need to set custom authentication backend. As the problem is occurring when authenticating the email and password, it’s giving None result.