csrf verification error for django admin login

Hi
I have just created a new Django project and am getting a csrf verification error (403) when trying to log into django admin.


The setup steps I have taken are:

  1. pip3 install django - django 4.0.1 is installed.
  2. django-admin startproject myprojectname - myprojectname is successfully created.
  3. python3 manage.py runserver - Server starts and django verification page is rendered.
  4. python3 manage.py migrate - Migrations are applied ok
  5. python3 manage.py createsuperuser - superuser is created successfully.
  6. python3 manage.py runserver and append ‘/admin/’ to url - Django admin login page is rendered ok
  7. Enter superuser name and password to log in - csrf verification failed, 403 error

Steps taken to resolve the issue are:

  1. I have checked in the dev tools for the csrf token and it is applied via a hidden field in the login form as expected.
  2. I have cleared the session cookies and have applied a hard refresh of the page and retried to login but the error remains.
  3. I have opened the project in another browser but the error remains.
  4. I have opened a previous django project (uses django v3.1.2) and set a new superuser and logged in without any errors.

I am at a loss as to what further steps I can take to resolve this issue so any help on this matter is gratefully accepted.

1 Like

See the CSRF_TRUSTED_ORIGINS setting.

1 Like

Thank you very much Ken, that solved it :-)…an instruction to that setting in Django docs tutorials would be helpful as it’s new in v4.0 as far as I can tell.

It is new to 4.0. However, as far as the tutorial is concerned, I’m not sure where it applies.

The tutorial is written for making http requests to localhost. I don’t see anything in the tutorial discussing https or dns-resolved hostnames - those are topics typically encountered much later.

I have the same problem and i tried all the things above
but i didn’t understnad what i should do in csrf_trusted_origins ?

what i should do here ?

I would suggest you open a new topic for your issue, along with all the relevant details regarding your specific situation. This topic has been marked as solved and isn’t likely to attract a lot of attention.

I am using vps and currently facing this issue in production. On localhost it works fine but when in production server it behaves this way. I don’t know what to do actually the logic behind the CSRF_TRUSTED_ORIGINS = [’ ', ’ '] do I need to comment out the ALLOWED_HOST = in replacement for this or that I need to include the CSRF_TRUSTED_ORIGINS …

Yes you do need CSRF_TRUSTED_ORIGINS and ALLOWED_HOSTS, both as described on the links above.

If you need more specific information, please open a new issue.