djangorestframework (내가 좋아하는)를 사용하고 있으며 프런트 엔드에서 REST 뷰/serializer로 데이터를 받아들이려고 기다리는 중 일부 데이터를 POST하려고합니다.Django-Rest-Framework POST 개체 필드 필요
REST API 백엔드에 로그인하면 (사용자가 검색어를 테스트 할 수 있도록 장고 준비가되어 있음)이 정보를 제출할 수 있으며 정보를 백엔드에 성공적으로 전달하고 객체를 저장합니다. :
{"goal": ["This field is required."]}
은 그래서 흥미 : 나는 POST 요청을 실행할 때
{
"user": 1,
"content": "this is some content",
"goal":
{
"competencies[]": [
32
],
"active": false,
"completed": false,
"user": 1
}
}
그러나, 그것은한다는 실패합니다. 그것은 백 엔드에서 작동하지만 정면에서는 작동하지 않습니다.
여기에 추가 도움을 내 코드입니다 :
//the ajax request
$.ajax({
// obviates need for sameOrigin test
crossDomain: false,
//adds a CSRF header to the request if the method is unsafe (the csrfSafeMethod is in base.html)
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
//needed because we're setting data, I think.
type: "POST",
//target API url
url: '/api/goal-status/add',
data: this_instead,
//on success, reload the page, because everything worked
success: function(){
location.reload();
alert("In the goal-add click listener");
},
//we'll have to find something better to do when an error occurs. I'm still thinking through this. There will probably just have to be some standardized way of going about it.
error: function(){
alert('An error ocurred!');
}
});
그리고이 요청에 응답 뷰입니다 :
class AddGoalStatus(generics.CreateAPIView):
serializer_class = GoalStatusSerializer
permission_classes = (
permissions.IsAuthenticated,
)
그리고 해당 모델 :
class Goal(TimeStampedModel):
"""A personalized Goal that a user creates to achieve"""
completed = models.BooleanField(default=False)
user = models.ForeignKey(User)
competencies = models.ManyToManyField(CoreCompetency)
def __unicode__(self):
return self.user.get_full_name()
class GoalStatus(TimeStampedModel):
"""As goals go on, users will set different statuses towards them"""
content = models.TextField(max_length=2000)
goal = models.ForeignKey(Goal, related_name="goal_statuses")
def __unicode__(self):
return self.goal.user.get_full_name() + ": " + self.content
class Meta:
verbose_name_plural = "Statuses"
verbose_name = "Goal Status"
그리고 완전을 위해 serializer가 있습니다 :
class GoalSerializer(serializers.ModelSerializer):
competencies = serializers.PrimaryKeyRelatedField(many=True, read_only=False)
class Meta:
model = Goal
class GoalStatusSerializer(serializers.ModelSerializer):
goal = GoalSerializer()
class Meta:
model = GoalStatus