from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework.authtoken.models import Token
from faker import Faker
fake = Faker()
APICLIENT = APIClient()
from factory_djoy import UserFactory
class TestAccount(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_print_name(self):
print(self.user.is_authenticated)
# do something here
why print(self.user.is_authenticated) is True. I have tried to create a user using simply User.objects.create it also returns the same as is_authenticated to True.
My understanding is that it should be not be True before doing login or force_authenticate. What am I doing wrong or is my understanding not correct?
.is_authenticated
does not mean that the user is authenticated on the server side. All User
objects have is_authenticated = True
, it is used to make a distinction between an User
[Django-doc] object, and the AnonymousUser
[Django-doc].
Indeed, by default if you look for request.user
, it will either return an AnonymousUser
object if there is no user attached to the setting, or a User
object if the session is bound to that user.
For the builtin User
model, .is_autenticated
will thus always return True
[GitHub]:
@property def is_authenticated(self): """ Always return True. This is a way to tell if the user has been authenticated in templates. """ return True
You can however define your own custom user model, and define a more sophisticated test: for example only users with is_active
can be authenticated, or users can only be authenticated if these have been active the last two months for example.
If you write in a view if user.is_authenticated
, it will thus for the builtin user model make a distinction between an AnonymousUser
(that will return False
), and a User
. But you can define a custom user model with a custom implementation.