I am creating CRUD operation in Django, REST API and Mongo DB. I have done the basic CRUD code. When I try to call the api in postman, I am not getting any responses.
In the pycharm, I am seeing the below issue,
"POST /emp/registration%0A HTTP/1.1" 404 2297
Not Found: /emp/registration
Here is my project structure.
DjangoAPI.urls.py
from django.urls import path
from django.urls import re_path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/', include('EmployeeApp.urls')),
]
DjangoAPI.EmployeeApp.urls.py
from EmployeeApp import views
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path
urlpatterns = [
path('registration', views.registrationApi),
]
DjangoAPI.settings.py
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
BASE_DIR=Path(__file__).resolve(strict=True).parent.parent
MEDIA_URL='/Photos/'
MEDIA_ROOT=os.path.join(BASE_DIR,"Photos")
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-@oxx-o(4f=mxha%-tlv97)x9m7x_fw=(@*k=*29q%r7c8*)%-&'
# 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',
'rest_framework',
'corsheaders',
'EmployeeApp.apps.EmployeeappConfig'
]
CORS_ORIGIN_ALLOW_ALL = True
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',
]
ROOT_URLCONF = 'DjangoAPI.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 = 'DjangoAPI.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'CLIENT': {
"host":"mongodb+srv://xxxxx:[email protected]/?retryWrites=true&w=majority"
,"name":"expense_tracker_v2",
"authMechanism":"SCRAM-SHA-1" #For atlas cloud db
}
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
models.py
from django.db import models
class Registrations(models.Model):
RegistrationId = models.AutoField(primary_key=True)
Username = models.CharField(max_length=200, unique=True)
Email = models.EmailField(unique=True)
Password = models.CharField(max_length=200)
views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from EmployeeApp.models import Registrations
from EmployeeApp.serializers import RegistrationsSerializer
@csrf_exempt
def registrationApi(request, id=0):
if request.method == 'GET':
registrations = Registrations.objects.all()
departments_serializer = RegistrationsSerializer(registrations, many=True)
return JsonResponse(departments_serializer.data, safe=False)
elif request.method == 'POST':
department_data = JSONParser().parse(request)
departments_serializer = RegistrationsSerializer(data=department_data)
if departments_serializer.is_valid():
departments_serializer.save()
return JsonResponse("Added Successfully", safe=False)
return JsonResponse("Failed to Add", safe=False)
elif request.method == 'PUT':
department_data = JSONParser().parse(request)
department = Registrations.objects.get(DepartmentId=department_data['DepartmentId'])
departments_serializer = RegistrationsSerializer(department, data=department_data)
if departments_serializer.is_valid():
departments_serializer.save()
return JsonResponse("Updated Successfully", safe=False)
return JsonResponse("Failed to Update")
elif request.method == 'DELETE':
department = Registrations.objects.get(DepartmentId=id)
department.delete()
return JsonResponse("Deleted Successfully", safe=False)
If I call this [http://127.0.0.1:8080/emp/registration][2] url in Postman (PUT) method, I am getting the url not found error.
and here’s my data:
{
"Username":"Soban",
"Email":"[email protected]",
"Password":"soban"
}
how can I do CRUD operations? Any help would be really appriciated.
Error message:
"POST /emp/registration%0A HTTP/1.1" 404 2297
Not Found: /emp/registration
2
Answers
The problem is that none of the paths in
DjangoAPI.EmployeeApp.urls.py
look like the URL that you’re calling from Postman. The list of paths needs another pattern added that matches the path when it includes an ID, like you use for the PUT call.The second path includes
<int:id>
, which tells Django that it should capture an integer located at that position in the path and send it to the view as a keyword argument calledid
. Including multiple paths that both point to the same view is a common way to allow optional arguments that are used by some calls (like PUT) but not others (like POST).Read more in the Django docs: https://docs.djangoproject.com/en/4.2/ref/urls/
Consider ending the path with a forward slash.