Django+MongoDB REST API调用404错误及CRUD实现求助
问题修复方案
核心问题诊断
- URL格式错误:日志中出现
/emp/registration%0A,%0A是换行符,说明请求URL中存在多余换行,导致路由匹配失败 - 路由配置不完整:当前路由仅支持无参数的请求,PUT/DELETE操作需要携带ID参数但未配置对应路由
- 视图字段与模型不匹配:视图中错误使用
DepartmentId字段,而模型中实际字段为RegistrationId - 变量名混淆:视图中多处将
registration错误命名为department,导致逻辑混乱
修复步骤及代码修正
1. 修正路由配置(EmployeeApp/urls.py)
添加带ID参数的路由,支持PUT/DELETE操作:
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), path('registration/<int:id>', views.registrationApi), # 新增带ID的路由 ]
2. 修正视图函数(EmployeeApp/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() registrations_serializer = RegistrationsSerializer(registrations, many=True) return JsonResponse(registrations_serializer.data, safe=False) elif request.method == 'POST': registration_data = JSONParser().parse(request) registrations_serializer = RegistrationsSerializer(data=registration_data) if registrations_serializer.is_valid(): registrations_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse(f"Failed to Add: {registrations_serializer.errors}", safe=False) elif request.method == 'PUT': registration_data = JSONParser().parse(request) try: registration = Registrations.objects.get(RegistrationId=registration_data['RegistrationId']) registrations_serializer = RegistrationsSerializer(registration, data=registration_data) if registrations_serializer.is_valid(): registrations_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse(f"Failed to Update: {registrations_serializer.errors}", safe=False) except Registrations.DoesNotExist: return JsonResponse("Registration not found", safe=False) elif request.method == 'DELETE': try: registration = Registrations.objects.get(RegistrationId=id) registration.delete() return JsonResponse("Deleted Successfully", safe=False) except Registrations.DoesNotExist: return JsonResponse("Registration not found", safe=False)
3. 修正请求规范
- POST请求:使用URL
http://127.0.0.1:8000/emp/registration(若自定义端口则替换为对应端口,如8080),方法选POST,传入如下JSON:{ "Username":"Soban", "Email":"soban@gmail.com", "Password":"soban" } - PUT请求:使用URL
http://127.0.0.1:8000/emp/registration/<实际RegistrationId>,方法选PUT,需在JSON中携带RegistrationId字段 - DELETE请求:使用URL
http://127.0.0.1:8000/emp/registration/<实际RegistrationId>,方法选DELETE - GET请求:使用URL
http://127.0.0.1:8000/emp/registration,方法选GET,获取所有注册数据
内容的提问来源于stack exchange,提问作者Raj De Inno
相关产品推荐
相关产品推荐

