简体   繁体   English

Django-Rest-Framework POST对象字段必填

[英]Django-Rest-Framework POST Object Field Required

I'm using djangorestframework (which I love) and I am attempting to POST some data from the front end to the REST view/serializer waiting to accept it. 我正在使用djangorestframework(我很喜欢),并且尝试将一些数据从前端发布到REST视图/序列化器,以等待接受它。

When I log into the REST API back end (that django rest provides for users to be able to test their queries), I can submit this information, and it will successfully pass the information to the back end and save the object: 当我登录REST API后端(django rest为用户提供了能够测试其查询的功能)时,我可以提交此信息,它将成功将信息传递给后端并保存对象:

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

But, when I run the POST request, it fails, stating that: 但是,当我运行POST请求时,它失败,说明:

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

So that's interesting. 这很有趣。 It works from the back end, but not the front. 它从后端开始工作,而不是从前端开始工作。

Here's my code for added help: 这是我的代码,可提供更多帮助:

//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!'); 
        }
    });

And this is the view that is responding to the request: 这是响应请求的视图:

class AddGoalStatus(generics.CreateAPIView): 
serializer_class = GoalStatusSerializer
permission_classes = (
    permissions.IsAuthenticated, 
)

And the corresponding models: 以及对应的型号:

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"

And here's the serializer for completeness: 这是完整性的序列化器:

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

As Tom Christie says in here: 正如汤姆·克里斯蒂(Tom Christie)在这里所说:

django rest framework create nested objects "Models" by POST django rest框架通过POST创建嵌套对象“模型”

Django Rest Framework does not allow you to write to a nested serializer. Django Rest Framework不允许您写入嵌套的序列化程序。

It looks like there is work being done on building out this functionality, but I don't know if it is done yet: 似乎在构建此功能方面正在完成工作,但我不知道是否已完成:

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

In the meantime see this thread for ideas on how to work around this limitation: 同时,请参见此主题以获取有关如何解决此限制的想法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django-Rest-Framework字段命名重映射 - Django-Rest-Framework field naming remap django-rest-framework中保存object的问题 - Problem with saving object in django-rest-framework Django-Rest-Framework,POST操作:字段不为空,但DRF表示必填 - Django-Rest-Framework, POST operation: fields is not empty but DRF says is required Django-Rest-Framework:如何使用request.user为登录用户发布到foreignkey字段 - Django-Rest-Framework: How to post to foreignkey field using request.user for logged in user 在 Django-Rest-Framework POST 调用中,它更新了多对多字段,适用于 JSON 但不适用于表单数据 - In Django-Rest-Framework POST call which updates manytomany field works with JSON but not with form-data django-rest-framework 如何使模型序列化器字段成为必需 - django-rest-framework how to make model serializer fields required django-rest-framework中Django外键字段中的完整性错误 - Integrity error in django foreign key field in django-rest-framework 发布到Django rest Framework API,但始终会收到“此字段为必填”错误 - Post to Django rest framework API but always get a 'This field is required' error 使用视图的django-rest-framework通过POST返回500 - django-rest-framework using views returns 500 with a POST 如何制作一个采用POST数据的Django-Rest-Framework API? - How to make a Django-Rest-Framework API that takes POST data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM