Login with code when using LiveServerTestCase with Django

You can’t login user from selenium driver. It’s just impossible without some hacks.

But you can login once per TestCase by moving it to setUp method.

You can also avoid copy-pasting by creating your class inherit from LiveServerTestCase.

UPDATE

This code worked for me:

self.client.login(username=superuser.username, password='superpassword') #Native django test client
cookie = self.client.cookies['sessionid']
self.browser.get(self.live_server_url + '/admin/')  #selenium will set cookie domain based on current page domain
self.browser.add_cookie({'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': "https://stackoverflow.com/"})
self.browser.refresh() #need to update page for logged in user
self.browser.get(self.live_server_url + '/admin/')

Leave a Comment