"<field>": [ "이 필드는 필수입니다."] 메시지 Django REST 프레임 워크
그래서 오늘 저는 프로젝트에 처음으로 Django REST 프레임 워크를 구현하려고 시도했습니다. 모든 것이 잘 작동하고 있습니다. 프레임 워크가 제공하는 브라우저 인터페이스를 사용하여 게시물을 생성, 업데이트 및 삭제할 수 있지만 JWT 토큰을 통합 한 후 curl을 사용하여 게시물을 작성하려고하면 항상 "": [ "이 필드는 필수입니다."] 메시지가 표시됩니다. 여러 가지 방법으로 문제를 해결하려고 시도했지만 올바르게 필요한 필드를 구문 분석 할 방법이 없습니다. curl을 사용하여 Post를 만들 수도 있었지만 필드를 모두 "null"로 수정해야했습니다. 잘못된 컬 요청을 보내고 있습니까?
curl : (내가 -H "Content-Type : application / json"을 추가 {"detail":"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"}
하면 여기서 이미 해결 된 이 출력 을 얻습니다. 여기서 Json 구문 분석 오류 는 콘텐츠 유형 헤더를 제거하여 django rest api에서 POST를 사용하여 오류가 발생합니다 ) edit : ignore what 콘텐츠 유형 헤더가 필요하다고 방금 말했는데 내 부분에 대한 오해였습니다.
curl -X POST -H "Authorization: JWT <token>" -d '{
"title": "Helloooo",
"content": "Hi",
"schools": null,
"course": null,
"classes": [
1
],
"isbn": 12312,
"semester": null,
"visible": false
}' 'http://127.0.0.1:8000/api/posts/create/?type=post'
이것은 POST 요청을 보낸 후 터미널에서 얻은 출력입니다.
{"title":["This field is required."],"content":["This field is required."],"classes":["This list may not be empty."]}
나머지 코드는 다음과 같습니다.
직렬 변환기 :
class PostCreateSerializer(ModelSerializer):
date_posted = serializers.HiddenField(default=timezone.now)
class Meta:
model = Post
fields = [
"title",
"content",
"schools",
"course",
"classes",
"isbn",
"semester",
"visible",
"date_posted",
]
견해:
class PostCreateAPIView(CreateAPIView):
queryset = Post.objects.all()
serializer_class = PostCreateSerializer
def perform_create(self, serializer):
serializer.save(author=self.request.user)
URL :
urlpatterns = [
path(r"", PostListAPIView.as_view(), name="List-API"),
path("create/", PostCreateAPIView.as_view(), name="Create-API") ]
설정 :
REST_FRAMEWORK = {
"DEFAULT_RENDERER_CLASSES": [
"rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer",
],
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication",
"rest_framework_jwt.authentication.JSONWebTokenAuthentication"
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated"
],
}
시간을내어 읽어 주셔서 감사합니다!
답변
문제는 아마도 curl 요청에있을 것입니다 . 대신 Postman
을 사용하는 것이 좋습니다 . 그러나 curl 을 사용하려면 JSON 콘텐츠 유형으로 본문을 보내기 위해 요청 헤더에서 확인해야합니다. Windows OS에서는 작은 따옴표를 사용하여 JSON 본문을 확인할 수 없습니다. 대신 이것을 시도하십시오.
curl -X POST \
-H "Authorization: JWT <token>" \
-H "Content-Type: application/json" \
-d "{
\"title\": \"Helloooo\",
\"content\": \"Hi\",
\"schools\": null,
\"course\": null,
\"classes\": [
1
],
\"isbn\": 12312,
\"semester\": null,
\"visible\": false
}" http://127.0.0.1:8000/api/posts/create/?type=post
Seyyed Sajjad Sanikhani 덕분에 결국 문제를 해결했습니다. 실제로 powershell에서 올바른 따옴표와 패딩을 사용하여 콘텐츠 유형을 지정해야했는데 최종 코드는 다음과 같습니다.
curl -X POST -H "Authorization: JWT <token>" -H "Content-Type: application/json" -d '{
\"title\": \"Hello there\",
\"content\": \"high ground\",
\"schools\": "1",
\"course\": "1",
\"classes\": [
"1"
],
\"isbn\": 12312,
\"semester\": "1",
\"visible\": true
}' 'http://127.0.0.1:8000/api/posts/create/?type=post'
마지막으로 출력은 다음과 같습니다.
{"title":"Hello there","content":"high ground","schools":1,"course":1,"classes":[1],"isbn":12312,"semester":1,"visible":true}
따라서 다음 오류가 발생할 수 있으므로 요청에주의하십시오.
"detail": "JSON parse error - Expecting property name enclosed in double-quotes"
또는
"[globbing] nested brace in column"