Paul Nurkkala
Paul Nurkkala

Reputation: 13

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.

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:

{
        "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:

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

Upvotes: 1

Views: 1788

Answers (1)

dvcolgan
dvcolgan

Reputation: 7728

As Tom Christie says in here:

django rest framework create nested objects "Models" by POST

Django Rest Framework does not allow you to write to a nested serializer.

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

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

Upvotes: 1

Related Questions