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:

login.html

{% 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">
      <input
        type="email"
        name="email"
        id=""
        class="outline-1 rounded-md p-4 w-[80%] mb-4"
        placeholder="Enter Email"
      />
    </div>
    <div class="password">
      <input
        type="password"
        name="password"
        id=""
        class="outline-1 rounded-md p-4 w-[80%] mb-4"
        placeholder="Enter Password"
      />
    </div>
</div>
    <div class="w-[80%] mx-auto">
      <button
        type="submit"
        class="bg-indigo-500 hover:bg-indigo-600 px-8 py-4 rounded-md text-white"
      >
        LOGIN NOW
      </button>
    </div>
  </form>
</div>
{% endblock content %}

forms.py

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'
    }))

models.py

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):
        return self.name


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):
        return self.name

urls.py

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'),
]

views.py

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 = {
        'products':products,
        'categories':categories,
    }
    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():
            user.save()
            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')

        try:
            user = User.objects.get(email=email)
        except:
            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):
    logout(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/exception.py", 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/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/website/page/views.py", 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/__init__.py", line 138, in login
    request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
  File "/Volumes/Programming/Custom Tool by Django/Online Marketplace/venv/lib/python3.10/site-packages/django/utils/functional.py", 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.