Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, can't log in after creating user

I created user in the Django shell and tried to authenticate it, but can't. That returns NoneType. Also, I check that is_superuser, is_stuff, is_active is True

>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate
>>> User.objects.create(username='user', password='password', email='someemail')
>>> User.objects.all()
>>> <QuerySet [<User: admin>, <User: user>]>
>>> admin
>>> user = authenticate(username='user', password='password')
>>> user
>>> user.is_active
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'is_active'
>>> type(user)
<class 'NoneType'>
>>> admin = authenticate(username='admin', password='wa23sd54fg')
>>> admin
<User: admin>
>>> admin.is_active()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'bool' object is not callable
>>> admin.is_active
True

>>> user = User.objects.get(pk=2)
>>> user
<User: user> 
>>> user.is_active
True
>>> user.is_superuser
True
>>> user.is_staff
True

When tried log in with use in admin panel, it shows the error:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

like image 997
Denis Svistunov Avatar asked Apr 17 '18 15:04

Denis Svistunov


People also ask

How do I login as user in Django?

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...


1 Answers

You should have used the create_user method, so that the password was hashed correctly:

User.objects.create_user(username='user', password='password', email='someemail')

If you want the user to be able to access the Django admin, set is_staff=True as well:

User.objects.create_user(username='user', password='password', email='someemail', is_staff=True)

You can fix the password for the existing user in the Django shell with set_password:

user = User.objects.get(username='user')
user.set_password('password')
user.is_staff = True  # allow user to log in to Django admin
user.save()
like image 181
Alasdair Avatar answered Sep 21 '22 01:09

Alasdair