You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中GET请求正常但POST请求提示用户不存在问题排查

POST请求提示用户不存在但GET请求正常的原因及解决办法

问题现象

  • 向http://127.0.0.1:8000/user_ques_management/add_favorite_question/发送JSON格式的POST请求,返回{"error": "User not found."},终端日志显示Received POST data: <QueryDict: {}>、Received idname: None
  • 使用同一用户的user_id向http://127.0.0.1:8000/user_ques_management/favorite_read_questions/3486/发送GET请求,能正常获取用户的收藏/已读问题数据

核心原因

Django的request.POST仅支持解析**表单编码(application/x-www-form-urlencoded)**的请求体,而你发送的是JSON格式(请求头Content-Type为application/json)的请求,因此request.POST无法读取到JSON数据,导致idname取值为None,最终触发UserProfile.DoesNotExist异常,返回用户不存在的错误。

解决方案

修改add_favorite_question视图,直接解析request.body中的JSON数据,替代request.POST的取值方式:

import json
from django.http import JsonResponse
from .models import UserProfile, Question, FavoriteQuestion

@csrf_exempt
def add_favorite_question(request):
    if request.method == 'POST':
        # 解析JSON格式的请求体
        try:
            data = json.loads(request.body)
            idname = data.get('idname')
            question_id = data.get('question_id')
            print("Received idname:", idname)
        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON data.'}, status=400)

        try:
            user = UserProfile.objects.get(idname=idname)
            question = Question.objects.get(id=question_id)

            FavoriteQuestion.objects.create(user_id=user, question_id=question)
            return JsonResponse({'message': 'Favorite question added successfully.'})
        except UserProfile.DoesNotExist:
            return JsonResponse({'error': 'User not found.'}, status=404)
        except Question.DoesNotExist:
            return JsonResponse({'error': 'Question not found.'}, status=404)

额外说明

GET请求正常是因为它通过URL路径参数传递user_id,不需要解析请求体,视图直接从URL捕获参数并查询数据库,因此不受请求体格式影响。

内容的提问来源于stack exchange,提问作者Prince Zuko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:37:38