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

**URL:** <https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681>\
**Category:** Forms & APIs\
**Created:** [February 6, 2023, 11:54pm UTC](https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681 "2023-02-06T23:54:33Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![robert24hp](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/robert24hp/32/12082_2.png) [@robert24hp](https://forum.djangoproject.com/u/robert24hp)\
**Post date:** [February 6, 2023, 11:54pm UTC](https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681/1 "2023-02-06T23:54:33Z")

</div>

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**

```auto
{% 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**

```auto
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**

```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):
        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**

```auto
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**

```auto
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')

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 6, 2023, 11:57pm UTC](https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681/2 "2023-02-06T23:57:38Z")

</div>

Please post the complete traceback that you are receiving.

---

<div class="post-metadata">

**Author:** ![robert24hp](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/robert24hp/32/12082_2.png) [@robert24hp](https://forum.djangoproject.com/u/robert24hp)\
**Post date:** [February 7, 2023, 12:06am UTC](https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681/3 "2023-02-07T00:06:43Z")

</div>

Thanks for the reply Ken.

Here is the complete traceback from VS Code:

```auto
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'

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 7, 2023, 3:07am UTC](https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681/4 "2023-02-07T03:07:44Z")

</div>

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

Are you using a [custom authentication backend](https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#specifying-authentication-backends)?

If not, have you specified your [`USERNAME_FIELD`](https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD) for your [custom User model](https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#specifying-a-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](https://docs.djangoproject.com/en/4.1/topics/auth/default/#authenticating-users)

---

<div class="post-metadata">

**Author:** ![robert24hp](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/robert24hp/32/12082_2.png) [@robert24hp](https://forum.djangoproject.com/u/robert24hp)\
**Post date:** [February 7, 2023, 9:58am UTC](https://forum.djangoproject.com/t/django-authenticate-and-login-issue-anonymoususer-object-has-no-attribute-meta/18681/5 "2023-02-07T09:58:13Z")

</div>

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.
