# django4.2 post forbidden

**URL:** <https://forum.djangoproject.com/t/django4-2-post-forbidden/25075>\
**Category:** Mystery Errors\
**Created:** [November 6, 2023, 9:21am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075 "2023-11-06T09:21:31Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:21am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/1 "2023-11-06T09:21:31Z")

</div>

created a new project using Django 4.2.7. When I tested an API endpoint, I received a 200 response for a GET request, but a 403 Forbidden response for a POST request. I am using Python 3.10.11 with Django 4.2.7 and django-cors-headers 4.3.0. I followed the instructions on the django-cors-headers official website to configure CORS in my settings.py file and restarted the server, but I am still experiencing CORS issues. I am not a beginner developer. The specific error message is: Forbidden (CSRF cookie not set.)

```auto
INSTALLED_APPS add 'corsheaders'    
MIDDLEWARE add 'corsheaders.middleware.CorsMiddleware'
CORS_ALLOWED_ORIGINS = []
CORS_ALLOWED_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS',
]
CORS_ALLOWED_HEADERS = [
    'Accept',
    'Content-Type',
]
CORS_ALLOW_CREDENTIALS = True

```

urls.py

```auto
from django.contrib import admin
from django.urls import path
from qm import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
]

```

views.py

```auto
from django.http import HttpResponse

# Create your views here.

def index(request):
    if request.method == 'GET':
        return HttpResponse("123")
    if request.method == 'POST':
        return HttpResponse("456")
    else:
        return HttpResponse("789")

```

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [November 6, 2023, 9:27am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/2 "2023-11-06T09:27:59Z")

</div>

The error is not because of CORS, it is because of CSRF. In your settings add the url like this

```auto
CSRF_TRUSTED_ORIGINS=['http://127.0.0.1:8000',]

```

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:31am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/3 "2023-11-06T09:31:37Z")

</div>

I add CSRF\_TRUSTED\_ORIGINS = [‘[http://127.0.0.1:8000](http://127.0.0.1:8000)’, ] but 403 Forbidden (CSRF cookie not set.): /

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [November 6, 2023, 9:34am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/4 "2023-11-06T09:34:09Z")

</div>

Is there any specific page where you are getting this error.  
Also are you running your django project same as `http://127.0.0.1:8000` this url.

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:36am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/5 "2023-11-06T09:36:20Z")

</div>

this one startapp but i add CSRF\_TRUSTED\_ORIGINS = [‘[http://127.0.0.1:8000](http://127.0.0.1:8000)’, ]  
CSRF\_COOKIE\_SECURE = False  
CSRF\_COOKIE\_HTTPONLY = False in settings.py but error 403 Forbidden (CSRF cookie not set.): /

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:36am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/6 "2023-11-06T09:36:54Z")

</div>

urls.py  
from django.contrib import admin  
from django.urls import path  
from qm import views

urlpatterns = [  
path(‘admin/’, admin.site.urls),  
path(‘’, views.index, name=‘index’),  
]  
views.py  
from django.http import HttpResponse

# Create your views here.

def index(request):  
if request.method == ‘GET’:  
return HttpResponse(“123”)  
if request.method == ‘POST’:  
return HttpResponse(“456”)  
else:  
return HttpResponse(“789”)

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:37am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/7 "2023-11-06T09:37:54Z")

</div>

INSTALLED\_APPS = [  
‘django.contrib.admin’,  
‘django.contrib.auth’,  
‘django.contrib.contenttypes’,  
‘django.contrib.sessions’,  
‘django.contrib.messages’,  
‘django.contrib.staticfiles’,  
“corsheaders”,  
‘qm’,  
]

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

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:44am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/8 "2023-11-06T09:44:47Z")

</div>

no i get a forbidden

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 6, 2023, 9:49am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/9 "2023-11-06T09:49:45Z")

</div>

I put # ‘django.middleware.csrf.CsrfViewMiddleware’, The issue has been resolved.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 6, 2023, 12:03pm UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/10 "2023-11-06T12:03:13Z")

</div>

Side note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I have taken the liberty of correcting the original post, it may be helpful if you made the same changes to your other posts in this thread.)

> [@pythonliuwei-root](#):
>
> The issue has been resolved.

The issue has _not_ been resolved. You have now exposed your site to cross-site forgery request attacks, putting your users - and possibly your site - at risk.

How are you issuing the requests for the page throwing this error? Are you making requests using the browser or are you accessing your site with a JavaScript front end?

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 2:22am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/11 "2023-11-08T02:22:26Z")

</div>

Thanks KenWhitesell. I using postman post my django project api.  
Finally, I using django rest framework.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 8, 2023, 2:54am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/12 "2023-11-08T02:54:04Z")

</div>

Are you posting the csrf cookie along with the csrf token in your POST?

Also see the docs at [How to use Django’s CSRF protection | Django documentation | Django](https://docs.djangoproject.com/en/4.2/howto/csrf/#using-csrf-protection-with-ajax).

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 3:13am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/13 "2023-11-08T03:13:47Z")

</div>

I know from

```auto
 #my views.py
from django.views.decorators.csrf import csrf_exempt

@csrf_exampt 
def index(self, request):
     ...

```

help me. but I using django rest framework ‘rest\_framework.authentication.TokenAuthentication’.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 8, 2023, 3:18am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/14 "2023-11-08T03:18:51Z")

</div>

The issue might not be in your code. It might be in how you’re trying to issue the POST.

Are you posting the csrf cookie along with the csrf token in your POST?

Please show exactly what you are submitting as the request.

Note: The TokenAuthentication is something in addition to, and completely indepdentent of the CSRF-related elements.

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 3:44am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/15 "2023-11-08T03:44:02Z")

</div>

my code

```auto
# urls.py
from django.contrib import admin
from django.urls import path, include
from qm import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),

]
# qm/views.py
from django.http.response import JsonResponse

def index(request):
    return JsonResponse({"message": "ok"})

```

I use the code request below

```auto
import requests
res = requests.get("http://localhost:8000")
print(res.status_code)
# 403
```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 8, 2023, 3:46am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/16 "2023-11-08T03:46:07Z")

</div>

Try putting the trailing ‘/’ on the end of that URL (`"http://localhost:8000/"`)

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 5:28am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/17 "2023-11-08T05:28:57Z")

</div>

![image.png](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/9/8/981d1277a7fe14abd0bcc4d52e424802f62f45f5.png)

Ken Whitesell via Django Forum \<[notifications@djangoproject.discoursemail.com](mailto:notifications@djangoproject.discoursemail.com)\> 于2023年11月8日周三 11:56写道：

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 5:56am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/18 "2023-11-08T05:56:05Z")

</div>

# settings.py

```auto
"""
Django settings for xx project.

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

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

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
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+euvk!tcqw@yb0zthe5qhi8c48pl%a2vb=@)4l=r!(imlpda#%'

# 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',
    'x1',
]

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 = 'xx.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 = 'xx.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

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

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

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
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

```

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 5:56am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/19 "2023-11-08T05:56:50Z")

</div>

# urls.py

```auto
"""
URL configuration for xx project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import: from my_app import views
    2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
    1. Add an import: from other_app.views import Home
    2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from x1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
]

```

---

<div class="post-metadata">

**Author:** ![pythonliuwei-root](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pythonliuwei-root/32/16864_2.png) [@pythonliuwei-root](https://forum.djangoproject.com/u/pythonliuwei-root)\
**Post date:** [November 8, 2023, 5:57am UTC](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075/20 "2023-11-08T05:57:30Z")

</div>

# x1/views.py

```auto
from django.http.response import JsonResponse

def index(request):
    return JsonResponse({"message": "ok"})

```

[Next page](https://forum.djangoproject.com/t/django4-2-post-forbidden/25075.md?page=2)
