私はdjangorestframework(私が大好きです)を使用しており、フロントエンドからRESTビュー/シリアライザーにデータを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