2

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 Answers1

1

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)
EvilX
  • 426
  • 2
  • 5
  • True, i already had this implemented in between with data from the page in the browser, `csrfmiddlewaretoken` is a hidden field on the form. However of course the token is not static and changes on each request. Thanks! – anotherFishInTheTank Feb 01 '22 at 11:41