Title: Django test client: login doesn't work
Tags: python;django;django-views
Question: I'm having trouble logging in to test @login_required views in my Django test cases.
I have a CustomUser model that looks something like this:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', max_length=254, unique=True)
username = models.CharField('username', max_length=30, blank=True)
is_active = models.BooleanField('active', default=False, help_text='Designates whether this user should be treated as approved.')
objects = CustomUserManager()
USERNAME_FIELD = 'email'
Here's my test case:
class ViewTests(TestCase):
def test_create_user(self):
u = CustomUser.objects.create_superuser("michael77@example.com","p")
u.is_active = True
u.save()
def test_add_project(self):
self.client.login(username="michael77@example.com", password="p")
response = self.client.get(reverse('add-project'), {}, follow=True)
The user is created correctly and self.client.login() works, but the response is just a redirect to my login page.
I can create the user, log in correctly and use this view in a browser. How can I get the test client to do the same?

Here is the accepted answer: Each test method runs its own transaction which is rolled back at the end of the test. The data created in one test will not be available in another test. This login does not work because the user does not exist/was never created. If you need some common test data for your tests you can put that in the test case setUp.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:04/29/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><django><django-views>', 'Title': "Django test client: login doesn't work", 'ViewCount': 699, 'id': 29946229, 'user_AboutMe': None, 'user_AccountId': 2573794.0, 'user_DisplayName': 'kontextify', 'user_Reputation': 458.0, 'user_Views': 145.0, 'user_id': 2231950.0}}