Login to django admin via requests

Viewed 378

I want to log in on the django admin site via a python script using requests library.

From another posts' answer (here) i figured using a requests.Session() would be appropriate. However upon trying the following code, i get an 403 - forbidden status code.

url = 'url_to_django_admin_login_page'
payload = {'username': 'some_username', 'password': 'some_password'}

with reqeuests.Session() as s:
    r = s.post(url, data=payload)
    print(r)

>>> <Response [403]>

I checked credentials in the browser, so that should be fine.

For the keys in the payload dict i tried both values of the forms input fields keys name and id (i think name would be correct)

1 Answers

You forgot about CSRF

import requests

url = 'admin_url'

s = requests.Session()
s.get(url)
payload = {'username': 'admin', 'password': 'password', 'csrfmiddlewaretoken': s.cookies['csrftoken']}
r = s.post(url, data=payload)
print(r)
Related