Django URL问题,同时调用Postman

iqjalb3h  于 12个月前  发布在  Postman
关注(0)|答案(2)|浏览(197)

我正在Django,REST API和Mongo DB中创建CRUD操作。我已经完成了基本的CRUD代码。当我尝试在postman中调用API时,我没有得到任何响应。在pycharm中,我看到以下问题,

"POST /emp/registration%0A HTTP/1.1" 404 2297
 Not Found: /emp/registration

字符串
这是我的项目结构。
x1c 0d1x的数据
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. DjangeApp.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)


如果我在Postman(PUT)方法中调用这个[http://127.0.0.1:8080/emp/registration][2] url,我会得到url not found错误。
这是我的数据:

{
    "Username":"Soban",
    "Email":"[email protected]",
    "Password":"soban"
}


我如何做CRUD操作?任何帮助都将非常感谢。

错误信息:

“POST /emp/registration%0A HTTP/1.1”404 2297 Not Found:/emp/registration
http://127.0.0.1:8080/emp/registration

nkhmeac6

nkhmeac61#

问题是DjangoAPI.EmployeeApp.urls.py中没有一个路径看起来像您从Postman中调用的URL。路径列表需要添加另一个模式,当它包含ID时匹配路径,就像您在PUT调用中使用的那样。

urlpatterns = [
    path('registration', views.registrationApi),                  
    path('registration/<int:id>', views.registrationApi),                  
]

字符串
第二个路径包含<int:id>,它告诉Django它应该捕获位于路径中该位置的整数,并将其作为关键字参数id发送到视图。包含多个都指向同一视图的路径是一种常见的方式,允许某些调用(如PUT)使用可选参数,而其他调用(如POST)则不使用。
在Django文档中阅读更多:https://docs.djangoproject.com/en/4.2/ref/urls/

qhhrdooz

qhhrdooz2#

考虑用正斜杠结束路径。

urlpatterns = [
    •••
    path('registration/', views.registrationApi),
    •••
]

字符串

相关问题