Django Admin

131 views
Skip to first unread message

James Hunt

unread,
Mar 11, 2023, 1:04:40 PM3/11/23
to Django users
Hi there. I am fairly new to Django but have had previous success with creating an app and being able to access the Admin page.
Recently, if I attempt to access the admin page of a new Django app it throws the CSRF error upon trying to log in!!!

I have attempted several ways to bypass this error including adding allowed hosts but I cant seem to get past this issue.

Can someone please provide me with the definitive way of stopping CSRF error when simply trying to access the admin part of Django? I mean there are no post functions that really apply to this feature so I cant understand the CSRF token.

I cant get past this issue which means I can never access the admin page!!

Please help.

Regards

James

Balogun Awwal

unread,
Mar 11, 2023, 1:58:32 PM3/11/23
to django...@googlegroups.com
Check out this link but are you using csrf token before accepting any input.  https://stackoverflow.com/questions/3197321/csrf-error-in-django

Sent from awwal

On 11 Mar 2023, at 7:04 PM, James Hunt <newbyp...@gmail.com> wrote:

Hi there. I am fairly new to Django but have had previous success with creating an app and being able to access the Admin page.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e13c7765-831e-45c5-b091-c8fcfbed19c5n%40googlegroups.com.

Obam Olohu

unread,
Mar 11, 2023, 3:16:49 PM3/11/23
to django...@googlegroups.com
Hello there, you can send a meeting link, I’ll fix the issue for you 

Sent from my iPhone
--

Victor Matthew

unread,
Mar 11, 2023, 3:16:50 PM3/11/23
to django...@googlegroups.com
Show your cold pleased 


--

Letlaka Tsotetsi

unread,
Mar 11, 2023, 3:48:58 PM3/11/23
to django...@googlegroups.com
Please share your code so we can be able to assist you

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e13c7765-831e-45c5-b091-c8fcfbed19c5n%40googlegroups.com.
--
Letlaka Tsotetsi
071 038 1485
Letl...@gmail.com

Ahmed alhaiab

unread,
Mar 11, 2023, 3:59:10 PM3/11/23
to django...@googlegroups.com

Muhammad Juwaini Abdul Rahman

unread,
Mar 12, 2023, 5:46:04 AM3/12/23
to django...@googlegroups.com
I think you need to add the following in settings.py:

CSRF_TRUSTED_ORIGIN = ('<your_web_url>')



--

James Hunt

unread,
Mar 12, 2023, 8:32:10 AM3/12/23
to Django users
I have literally set this up today just to prove that it happens for every Django project setup!!!

So this is my settings :


 """
Django settings for DjangoTest project.

Generated by 'django-admin startproject' using Django 4.1.7.

For more information on this file, see

For the full list of settings and their values, see
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-zb-=l4$q!2t@wjwt!@cp#rz=16v0l)#uai#7h(u4n8eie@ddt%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DjangoTest.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DjangoTest.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)

STATIC_URL = 'static/'

# Default primary key field type

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


Muhammad Juwaini Abdul Rahman

unread,
Mar 12, 2023, 8:57:19 AM3/12/23
to django...@googlegroups.com
Have you tried my suggestion?

James Hunt

unread,
Mar 12, 2023, 9:05:17 AM3/12/23
to Django users
I did add this but no change!!! Just keep getting that CSRF token error when trying to access admin!! Which is strange as the CSRF token is predominantly for POST methods.

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

Mir Junaid

unread,
Mar 12, 2023, 11:06:42 PM3/12/23
to django...@googlegroups.com
try including this line in your index.html or main HTML page 
{% csrf_token %}
if it still doesn't work do include it in every html page

--

James Hunt

unread,
Mar 13, 2023, 5:14:22 AM3/13/23
to Django users
I have yet to create a HTML page so I'm not sure that the inclusion of {% csrf_token %} is required. I mean it's just the admin page I am trying to access which is provided by Django and not a page created by me!!!

I am very surprised there is no fix for this issue!!! I might need to abandon Django and move a different framework given that this issue is at the start of a project!!!

Cheers

Jay

Andrew Romany

unread,
Mar 13, 2023, 10:08:06 AM3/13/23
to django...@googlegroups.com
It's very simple you should add it in the login/register html page but inside the <form method='post'> tag after &  to be specific after this above line.

James Hunt

unread,
Mar 13, 2023, 1:03:57 PM3/13/23
to Django users
Hi there. I have yet to add a login/register page since I am only trying to access the admin page which is a part of the Django project setup. So in effect, there are no HTML pages setup and I cant access the Django admin page layout as this is an integral part of Django!!! This is the problem!! 

I'm not sure if anyone else who sets up a  Django project would need to create any HTML pages before they create a superuser login enabling them to access their admin section.

I cant resolve this issue!!

Cheers

J

Paul Kudla

unread,
Mar 13, 2023, 1:13:30 PM3/13/23
to django...@googlegroups.com

ok hope i am not adding to the confusion

I ran into this a while back

CSRF errors are usually (in my case anyways) triggered by apache SSL
setup etc

if you are running Apache + SSL you need to make sure the certificates
and the SNI ssl naming is setup correctly or the CSRF errors will
trigger randomly.

of course the ssl cert has to match the site name

this config assumes APACHE + WSGI + SSL etc. and you are running
multiple virtual sites under apache.

Also note the port 80 redirect (ie everything is directed to the SSL site)

if you are mixing ssl & non-ssl apache / django will get confused and
trip the CSRF error as well.

relative apache config (httpd.conf):

<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin

SSLSessionCache memcache:localhost:11211 <<-- only if using memcache.
</IfModule>


then my apache config for a site ?

admin.scom.ca ?

<VirtualHost *:80>
ServerName admin.scom.ca
ServerAlias admin.scom.ca
Redirect permanent / https://admin.scom.ca/
</VirtualHost>

<VirtualHost *:443>
ServerName admin.scom.ca
ServerAlias admin.scom.ca
DocumentRoot /www/admin.scom.ca

Alias /media/ /www/admin.scom.ca/media/
Alias /static/ /www/admin.scom.ca/statics/
Alias /statics/ /www/admin.scom.ca/statics/

<Directory "/www/admin.scom.ca/statics/">
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>

SSLEngine on
SSLProtocol all
SSLCertificateFile /www/admin.scom.ca/ssl/admin.scom.ca.crt
SSLCertificateKeyFile /www/admin.scom.ca/ssl/admin.scom.ca.key
SSLCertificateChainFile /www/admin.scom.ca/ssl/admin.scom.ca.chain



SuexecUserGroup www www

##Below only used if running WSGI##

WSGIDaemonProcess adminscomcassl user=www group=www processes=10 threads=20
WSGIProcessGroup adminscomcassl
WSGIApplicationGroup %{GLOBAL}
WSGIImportScript /www/admin.scom.ca/django.wsgi
process-group=adminscomcassl application-group=%{GLOBAL}

WSGIScriptAlias / /www/admin.scom.ca/django.wsgi

##End of WSGI##

<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

<Directory "/www/admin.scom.ca/wp-content/uploads/">
<Files "*.php">
Order Deny,Allow
Deny from All
</Files>
</Directory>

<Directory /www/admin.scom.ca>
php_admin_value open_basedir /www/admin.scom.ca:/var/log/
</Directory>

<Directory /www/admin.scom.ca>
php_admin_value sys_temp_dir /www/admin.scom.ca/tmp/
</Directory>

<Directory /www/admin.scom.ca>
php_admin_value session.save_path /www/admin.scom.ca/tmp/
</Directory>

<Directory /www/admin.scom.ca>
php_admin_value soap.wsdl_cache_dir /www/admin.scom.ca/tmp/
</Directory>

<Directory /www/admin.scom.ca>
php_admin_value upload_tmp_dir /www/admin.scom.ca/tmp
</Directory>

<Directory "/www/admin.scom.ca">
AllowOverride All
php_value session.save_path "/www/admin.scom.ca/"
</Directory>

</VirtualHost>







Happy Monday !!!
Thanks - paul

Paul Kudla


Scom.ca Internet Services <http://www.scom.ca>
004-1009 Byron Street South
Whitby, Ontario - Canada
L1N 4S3

Toronto 416.642.7266
Main 1.866.411.7266
Fax 1.888.892.7266
Email pa...@scom.ca
> <mailto:django-users...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/e13c7765-831e-45c5-b091-c8fcfbed19c5n%40googlegroups.com <https://groups.google.com/d/msgid/django-users/e13c7765-831e-45c5-b091-c8fcfbed19c5n%40googlegroups.com?utm_medium=email&utm_source=footer>.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAFKhtoRactd%2Bhg-3_m8d5MOKSYb0gp9J9m%2BjNM7naykJ8r3Kww%40mail.gmail.com <https://groups.google.com/d/msgid/django-users/CAFKhtoRactd%2Bhg-3_m8d5MOKSYb0gp9J9m%2BjNM7naykJ8r3Kww%40mail.gmail.com?utm_medium=email&utm_source=footer>.
>
> --
> This message has been scanned for viruses and
> dangerous content by *MailScanner* <http://www.mailscanner.info/>, and is
> believed to be clean.

Sandip Bhattacharya

unread,
Mar 13, 2023, 1:48:44 PM3/13/23
to django...@googlegroups.com


On Mar 13, 2023, at 5:14 AM, James Hunt <newbyp...@gmail.com> wrote:

I have yet to create a HTML page so I'm not sure that the inclusion of {% csrf_token %} is required. I mean it's just the admin page I am trying to access which is provided by Django and not a page created by me!!!

I am very surprised there is no fix for this issue!!! I might need to abandon Django and move a different framework given that this issue is at the start of a project!!!

There is clearly something else going on in your setup.

Here is a brand new Django project being created just now.

And the admin interface works without any issue.


Can you check if you missed any steps?

Thanks,
  Sandip

Starnford Chirwa

unread,
Mar 13, 2023, 4:00:01 PM3/13/23
to django...@googlegroups.com

Prosper Lekia

unread,
Mar 13, 2023, 4:32:43 PM3/13/23
to Django users
This is how I deal with all csrf related issues.

Make sure csrf MiddleWare is in your MiddleWare list 

'django.middleware.csrf.CsrfViewMiddleware'

Add the settings below in your settings.py to prevent all csrf related issues

CSRF_TRUSTED_ORIGINS = ['https://your site url',]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'http')
CSRF_USE_SESSIONS = False
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True


SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_FRAME_DENY = True
SECURE_HSTS_SECONDS = 2592000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
SECURE_REFERRER_POLICY = 'same-origin

Muhammad Juwaini Abdul Rahman

unread,
Mar 13, 2023, 8:39:27 PM3/13/23
to django...@googlegroups.com
In my previous case, I only use this:

CSRF_TRUSTED_ORIGINS = ['https://your site url',]

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Ikrombek

unread,
Mar 23, 2023, 10:20:37 PM3/23/23
to Django users

Hello,
How can I use dental teeth section. For example, do I need to include 32 fields from the model to specify 32 teeth, or is there a way to do it in one?

Jd Mehra

unread,
Mar 24, 2023, 8:35:26 AM3/24/23
to Django users
  • Clear the browser cache and cookies and then try to log in again. Sometimes an old CSRF token can be stored in the browser cache and can cause issues.


Reply all
Reply to author
Forward
0 new messages