Working on making some unittests with Django, and trying to make some testing with the login process with the login form.
I am using modified User
model just to make the email field unique; otherwise nothing drastically different.
def post(self, request):
# Retrieve the username and password
username = request.POST['username']
password = request.POST['password']
# Create a user object from authentication, or return None
user = authenticate(username=username, password=password)
# Check if user was created
if user is not None:
# Rest of the code, irrelevant...
from account.models import User as CustomUser
# Code snippit
def test_account_login_POST_successful_login(self):
# Create a user to test login
CustomUser.objects.create_user(
username='test_user',
email='test_user@intranet.com',
password='flibble'
)
response = self.client.post(self.login_url, {
'username': 'test_user',
'password': 'flibble'
})
self.assertEqual(response.status_code, 301)
class User(AbstractUser):
# Make the email field unique
email = models.EmailField(unique=True)
# Authentication
AUTH_USER_MODEL = 'account.User'
Funny thing is that login works normally on the web app, but when testing it always returns None
.
I've tried to check_password()
with the created user, and it returns true in both the test method and the view method.
I've also tried putting in AUTHENTICATION_BACKEND = ['django.contrib.auth.backends.ModelBackend']
, but no go.
I faced with the same problem. The problem was in is_active
model field. In my case this field was False
by default, so authenticate()
returns None
all the time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.