python - Django-Rest-Framework POST 对象字段必需

标签 python ajax django api rest

我正在使用 djangorestframework(我喜欢它),并且我正在尝试将一些数据从前端发布到等待接受它的 REST View /序列化器。

当我登录到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!'); 
        }
    });

这是响应请求的 View :

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

最佳答案

正如汤姆·克里斯蒂所说:

django rest framework create nested objects "Models" by POST

Django Rest Framework 不允许您写入嵌套序列化程序。

看起来正在开发此功能,但我不知道它是否已完成:

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

同时,请参阅此线程以获取有关如何解决此限制的想法:

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

关于python - Django-Rest-Framework POST 对象字段必需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19729438/

相关文章:

django - Celery 与 Django 和 MongoDB (mongoengine)

python - 没有实例的 Django Formset

python - 二进制到字符串,比字典好?

jquery - 显示/隐藏加载 GIF 无法使其工作

python - 无法在任何地方运行 jupyter(终端、anaconda 分发器)Mac os 10.12.6

javascript - jquery ajax 解析响应文本

javascript - Rails js 调用出现 404,可能是错误的路由定义

python - 在 Mountain Lion 中执行 ex mkvirtualenv 时出错

python - “ super ”对象没有属性 '_get_type_value'

python - 同时等待屏幕和通讯输入