Hello everyone,
This is my first post in Django forum, the issue I have is that I get server ouput error “POST /sections/ HTTP/1.1 404” every time I send a POST request from my Quasar client.
I checked the problem is on the server side, as the issue is that the server does not route the url with the view, as if I call “POST /section” I get the same error as “POST /sections” even though the path “/sections” is defined in “urls.py”.
I would really appreciate receiving help as I have been struggling with this error for days.
Next, I show my code files.
urls.py (from the app “blogApp”):
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path('sections/',views.create_section, name="create_section"),
path('newPost/', views.create_post, name="create_post"),
path('<str:section_name>/posts/', views.get_section_posts, name="get_section_posts"),
]
urls.py (from the project):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('blogApp/', include('blogApp.urls')),
path('admin/', admin.site.urls),
]
views.py:
from rest_framework.response import Response
from .models import Post, Section
from .serializers import PostSerializer, SectionSerializer
from django.shortcuts import render
from rest_framework.decorators import api_view
@api_view(['POST'])
def create_section(request):
serializer = SectionSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
@api_view(['POST'])
def create_post(request):
serializer = PostSerializer(data=request.data) # request.data contains the data sent in the request's body
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
@api_view(['GET'])
def get_section_posts(request, section_name):
try:
section = Section.objects.get(name=section_name)
posts = Post.objects.filter(section=section)
serializer = PostSerializer(posts, many=True)
return Response(serializer.data)
except Section.DoesNotExist:
return Response({"error": "Section not found"}, status=404)
def index(request):
return render(request, 'index.html')
settings.py
"""
Django settings for djangoBlog project.
Generated by 'django-admin startproject' using Django 5.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/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/5.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ma9_@z)cm6g$a%*$1&t^oqr()b6^#1=-d%c!)bma^r@_5j!s_x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]']
# Application definition
INSTALLED_APPS = [
"blogApp.apps.BlogappConfig",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'mongoengine',
'corsheaders',
]
MONGODB_SETTINGS = {
'ENGINE': 'django',
'DB': 'blogApp_DB',
'HOST': 'localhost',
'PORT': 27017,
}
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:9000", # Frontend's origin
"http://127.0.0.1:9000",
]
ROOT_URLCONF = 'djangoBlog.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 = 'djangoBlog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.1/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/5.1/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/5.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'