'AnonymousUser' object has no attribute '_meta'

Hi, I’m having problems with the above error. I am new to Django and learning as I go along. Any help will be greatly appreciated.

Views.py:

def loginUser(request):
    if request.user.is_authenticated:
        return redirect('profiles')

    if request.method == 'POST':
        username = request.POST['username'].lower()
        password = request.POST['password']

        try:
            user = User.objects.get(username=username)
        except:
            messages.error(request, 'Username does not exist!')

        user = authenticate(request, username=username, password=password)

        if user is not NONE:
            login(request, user)
            return redirect('profiles')
        else:
            messages.error(request, 'Username or password is incorrect!')

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

login.html:

{% extends 'main.html' %}

{% block content %}

<h1>You are not logged in!</h1>
<br></br>

<form action="{% url 'login' %}" method="POST">
    {% csrf_token %}
    <input type="text" name="username" placeholder="Username"/>
    <input type="password" name="password" placeholder="Enter Password"/>
    <input type="submit" value="Login"/>
</form>

{% endblock content %}

Full error listing:

Internal Server Error: /login/
Traceback (most recent call last):
  File "/Users/paulbritten/.pyenv/versions/pafdadi/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/paulbritten/.pyenv/versions/pafdadi/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Volumes/Samsung_T5/MDU_Projects/Django_Projects/PAFDADI_Web_App/pafdadi-webapp/pafdadi/users/views.py", line 26, in loginUser
    login(request, user)
  File "/Users/paulbritten/.pyenv/versions/pafdadi/lib/python3.9/site-packages/django/contrib/auth/__init__.py", line 138, in login
    request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
  File "/Users/paulbritten/.pyenv/versions/pafdadi/lib/python3.9/site-packages/django/utils/functional.py", line 259, in inner
    return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute '_meta'

From reading similar issues on forums I know the issue would appear to be the interaction between:

user = authenticate(request, username=username, password=password)

and

login(request, user)

The only thing is I don’t have enough understanding of these interactions and I can’t make any of the changes required to make my code work.

All the best,

Paul

Can I assume that in your real code you have None and not NONE? (That’s the first thing to check and the only thing I see wrong at the moment.)

If that’s not it, then I’d start with the common debugging techniques of either using the debugger to see what the values are at each step, or tossing some print statements in there to see what is happening at each stage.

Also, you really don’t want to perform a check for the username separate from the password. It becomes a potential vector for attack.

In a real application, you’d also want these entries coming in from a form and not pulling them from request.POST directly. (The example you’re working from is designed to illustrate how to use the authenticate / login combination, not to provide a full example of a login view.)

Hi Ken,

D’oh! Thank you, I overlooked that. Didn’t see the wood from the trees there. Can you point me to a better example for using the authenticate / login combination from a form? Your help is greatly appreciated.

All the best,

Paul

A login form really isn’t any different than any other form.

I typically recommend people start with the Working with Forms docs, in this case paying particular attention to The view.

Your authenticate / logic combination would be handled in the is_valid branch.

Great, thanks again. I’ll look into changing using this approach.

Hello engineer KenWhitesell
I hope that you are well

I have a problem that I could not find a solution to, and I tried all methods to find a solution.
Notice the codes written below

The login page works, as I enter the username and password, then when I press the register button, nothing happens, it remains in the same place and the page did not change until it did not appear that I was registered.
Note that when I register as an admin, it appears in the top bar that I am registered
The problem is this doesn’t work for me…
{{ form.username|as_crispy_field }}
or i don’t understand

may you help me?

views.py

def user_login(request):
    if request.method =='POST':
        form = Login_Form()
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate (request, username=username, password=password)
        if user is not NONE:
            login(request, user)
            return redirect ('accounts:doctors_list')
    else:
        form = Login_Form()
    return render(request, 'user/login.html', {
        'form' : form
        })```

urls.py for app

from django.urls import path

from . import views

app_name = ‘accounts’

urlpatterns = [
# path(‘app/’, views.app, name=‘app’),
path(‘doctors/’, views.doctors_list, name=‘doctors_list’),
path(‘login/’, views.user_login, name=‘login’),
path(‘signup/’, views.signup, name=‘signup’),
path(‘myprofile/’, views.myprofile, name=‘myprofile’),
path(‘update_profile/’, views.update_profile, name=‘update_profile’),

path('<slug:slug>/', views.doctors_detail, name='doctors_detail'),

]

user_signup


forms.py

class Login_Form(forms.ModelForm):
username = forms.CharField(max_length=50, label=‘الاسم’)
password = forms.CharField(max_length=50, label=‘كلمة المرور’, widget=forms.PasswordInput())

class Meta:
    model = User
    fields = ['username', 'password']



models.py

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

from django.utils.translation import ugettext_lazy as _

from django.utils.translation import gettext as _

from django.db.models.signals import post_save

from django.utils.text import slugify

Create your models here.

TYPE_OF_PERSON = (
(‘M’,“Male”),
(‘F’,“Female”),
)

class Profile(models.Model):

DOCTOR_IN = {
    ('جلدية', "جلدية"),
    ('أسنان', "أسنان"),
    ('عظام', "عظام"),
    ('جراحة', "جراحة"),
    ('أطفال', "أطفال"),
    ('أعصاب', "أعصاب"),

}

user = models.OneToOneField(User, verbose_name=_("user"), on_delete=models.CASCADE)
name = models.CharField(_("الإسم :"), max_length=50, blank=True, null=True)
surname = models.CharField(_("اللقب :"), max_length=50, blank=True, null=True)
who_i = models.TextField(_("من أنا :"), max_length=500, blank=True, null=True)
price = models.IntegerField(_("سعر الكشف :"), blank=True, null=True)
image = models.ImageField(_("الصورة الشخصية"),upload_to='profile/', height_field=None, width_field=None, max_length=100,blank=True, null=True)
slug = models.SlugField(_("slug"), blank=True, null=True)

subtitle = models.CharField(_("نبذة عنك :"), max_length=50, blank=True, null=True)
address = models.CharField(_("المحافظة :"), max_length=50, blank=True, null=True)
address_detail = models.CharField(_("العنوان بالتفصيل :"), max_length=50, blank=True, null=True)
number_phone = models.CharField(_("الهاتف :"), max_length=50, blank=True, null=True)
working_hours = models.CharField(_("عدد ساعات العمل :"), max_length=50, blank=True, null=True)
Waiting_time = models.IntegerField(_("مدة الانتظار :"), blank=True, null=True)
doctor = models.CharField(_("دكتور؟ :"), choices = DOCTOR_IN, max_length=50, blank=True, null=True)
Specialist_doctor = models.CharField(_("متخصص في ؟  :"), max_length=100, blank=True, null=True)

facebook = models.CharField(_("حساب الفيس بوك :"), max_length=150, blank=True, null=True)
twitter = models.CharField(_("حساب تويتر :"), max_length=150, blank=True, null=True)
google =models.CharField(_("حساب قوقل :"), max_length=150, blank=True, null=True)

join_new = models.DateTimeField(auto_now_add=True,blank=True, null=True)
type_of_person = models.CharField(_("النوع :"), max_length=50, blank=True, null=True, choices = TYPE_OF_PERSON)

login.html

{% extends 'base.html' %}
{% load static %}

{% load crispy_forms_tags %}
{% comment %} {% load bootstrap4 %} {% endcomment %}









{% block body %}



<form class="container mt-5 p-5">



  <div dir="rtl">
    <div class="container mt-5 p-5">
        <div class="signup">
        <div class="col-md-9" >
            <form method="POST" enctype="multipart/form-data">
                <h4 class="auth-header">تسجيل الدخول</h4>
                {% csrf_token %}

                <div class="form-group">
                  {{ form.username|as_crispy_field }}
              </div>
                <div class="form-group">
                  {{ form.password|as_crispy_field }}
                </div>
                <div class="buttons-w  "><button type="submit" class="btn btn-success ml-5">تسجيل</button>
            </div>
            </form>
        </div>
        </div>
    </div>
    </div>
    



setting

Application definition

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘accounts’,
# ‘crispy_forms’,

# "crispy_bootstrap4",

"crispy_forms",
"crispy_bootstrap4",

]

CRISPY_ALLOWED_TEMPLATE_PACKS = “bootstrap4”

CRISPY_TEMPLATE_PACK = “bootstrap4”

TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
# ‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],
‘DIRS’: [‘templates’],
‘APP_DIRS’: True,
‘OPTIONS’: {
‘context_processors’: [
‘django.template.context_processors.debug’,
‘django.template.context_processors.request’,
‘django.contrib.auth.context_processors.auth’,
‘django.contrib.messages.context_processors.messages’,
],
},
},
]

Static files (CSS, JavaScript, Images)

How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django

STATIC_URL = ‘/static/’

STATICFILES_DIRS = [
BASE_DIR / “static”,
“/var/www/static/”,
]

MEDIA_URL = ‘/media/’
MEDIA_ROOT = os.path.join(BASE_DIR, “media”)

STATICFILES_DIRS = [os.path.join(BASE_DIR, “static”)]

Default primary key field type

Settings | Django documentation | Django

DEFAULT_AUTO_FIELD = ‘django.db.models.BigAutoField’

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))

BASE_DIR = Path(file).resolve().parent.parent

LOGIN_URL = ‘accounts:login’

This thread has been marked as solved. Your question is going to attract more attention if you open a new topic for it.

Note: When posting code or templates here, surround the code (or template) between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code (or template), then another line of ```. This forces the forum software to keep the text properly formatted.

try to add this to your settings.py

AUTH_USER_MODEL = ‘myapp.CustomUser’

it helped me