2013-11-01 2 views
1

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 

답변

1

톰 크리스티는 여기에 말한다 :

django rest framework create nested objects "Models" by POST

장고 나머지 프레임 워크가 중첩 된 직렬에 쓸 수 없습니다.

이 기능을 구축에서 수행되는 작업이있는 것처럼 보이지만, 아직 완료 모르겠어요 : 한편

https://github.com/tomchristie/django-rest-framework/tree/writable-nested-modelserializer

가하는 방법에 대한 아이디어를이 스레드를 참조 이 제한을 해결하려면 다음을 수행하십시오.

https://groups.google.com/forum/#!topic/django-rest-framework/L-TknBDFzTk