I am using Django REST framework. I have a model that looks like this:
class Post(models.Model):
title = models.CharField(max_length=100, null=False)
content = HTMLField()
created_at = models.DateField(auto_now_add=True)
authors = models.ManyToManyField(User)
With an api view and serializer that looks like this:
class CreateStoryApiView(CreateAPIView):
serializer_class = PostSerializer
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('title', 'content', 'authors')
Going to the actual endpoint, I can actually submit successfully. I am trying to use Ajax to take the details and submit the data to the endpoint, but for some reason I am always getting a 400 bad request error. If I remove the authors field, I don't have that error. Here's how the Ajax request looks like:
$.ajax({
type: 'POST',
url: '/api/save-post/',
data: {
"csrfmiddlewaretoken": getCookie('csrftoken'),
"title": "dasf",
"desct": "dasf",
"content": "fdasf",
"authors": [1,2]
},
success: function (msg) {
console.log(msg);
}
});
I get a 400 bad request when I try this Ajax request. Why can't I submit my array successfully? I've tried "authors[]": [1,2]
and "authors": "[1,2]"
and a lot of other combinations, but it seems like nothing is working for some reason. What am I doing wrong?