2013-11-01 106 views
1

我正在使用djangorestframework(我喜歡),我試圖從前端將一些數據發佈到等待接受它的REST視圖/序列化程序。Django-Rest-Framework POST對象字段必需

當我登錄到REST API後端(即django rest爲用戶提供了測試他們的查詢的能力時),我可以提交這些信息,並且它會成功地將信息傳遞到後端並保存對象:

{ 
     "user": 1, 
     "content": "this is some content", 
     "goal": 
     { 
      "competencies[]": [ 
      32 
      ], 
      "active": false, 
      "completed": false, 
      "user": 1 
     } 
    } 

但是,當我運行POST請求,失敗的話,指出:

{"goal": ["This field is required."]} 

所以這是有趣的。它從後端工作,但不是前端。

這裏是我的加入幫助代碼:

//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" 

而且這裏是序列化程序的完整性:

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

Django的REST框架不允許你寫一個嵌套的序列化。

它看起來像有打造出這個功能正在做的工作,但如果沒有完成,我不知道:

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

同時看到這個線程的想法如何解決此限制:

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

相關問題