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

Django REST Framework POST请求无法存储数据问题求助

Troubleshooting Your Django REST Framework POST Request Issue

Hey there! Let's break down why your POST request isn't saving valid data to the database, even after adjusting blank=True settings. Here are the most likely culprits and fixes:

1. Critical Issue: Incorrect created_at Default Value

Looking at your models.py, the created_at field has a bug in its default value:

# Wrong - this evaluates datetime.now() once when the server starts
created_at = models.DateTimeField(default=datetime.now())

This sets a fixed timestamp when your Django server boots up, not when a new Book object is created. This can cause unexpected validation or save failures.

Fix it with either of these options:

# Option 1: Use auto_now_add to automatically set creation time
created_at = models.DateTimeField(auto_now_add=True)

# Option 2: Pass the function reference (not the evaluated result)
created_at = models.DateTimeField(default=datetime.now)  # No parentheses!

2. Verify Postman Request Format

A common mistake is using the wrong content type in Postman, which leads to request.data being empty or malformed:

  • If sending JSON:
    • Go to the Headers tab and set Content-Type to application/json
    • In the Body tab, select raw → JSON and format your request like this:
      {
          "name": "The Great Gatsby",
          "store_name": "Book Haven",
          "description": "A classic novel",
          "fav": false
      }
      
  • If sending form data:
    • Select form-data in the Body tab, add your key-value pairs, and let Postman auto-set the multipart/form-data content type.

3. Debug with Print Statements

Add debug logs to your view to see exactly what's happening with the request and serializer:

class PostModelData(APIView):
    def post(self, request):
        # Check what data is actually received
        print("Received request data:", request.data)
        
        serializer = BookModelSerializers(data=request.data)
        if serializer.is_valid():
            print("Serializer passed validation!")
            saved_book = serializer.save()
            print("Saved book details:", saved_book.__dict__)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        # Print validation errors to identify missing/invalid fields
        print("Serializer errors:", serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Check your Django server console for these prints—they'll tell you if:

  • No data is coming through (request.data is empty)
  • The serializer is failing validation (and exactly which fields are problematic)

4. Double-Check Required Fields

If you removed blank=True from fields like name or store_name, they become required. Make sure you're sending all required fields in your Postman request—if any are missing, the serializer will return a validation error explaining which fields are needed.


内容的提问来源于stack exchange,提问作者Mohammad Js

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:53:13