Django REST Framework POST请求无法存储数据问题求助
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
Headerstab and setContent-Typetoapplication/json - In the
Bodytab, selectraw→JSONand format your request like this:{ "name": "The Great Gatsby", "store_name": "Book Haven", "description": "A classic novel", "fav": false }
- Go to the
- If sending form data:
- Select
form-datain theBodytab, add your key-value pairs, and let Postman auto-set themultipart/form-datacontent type.
- Select
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

