0

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?

user2896120
  • 3,180
  • 4
  • 40
  • 100
  • What error/response are you getting from API? – JPG Jun 25 '19 at 14:11
  • @JPG I'm just getting a 400 bad request. When I go to the Django REST endpoint and enter my data there, it works successfully and I can enter the authors as an array – user2896120 Jun 25 '19 at 14:23
  • I need to know the ***error response***. The 400 status code cloud be raised due to several reasons – JPG Jun 25 '19 at 14:26
  • @JPG Where can I find the error response? – user2896120 Jun 25 '19 at 14:55
  • Unfortunately, I don't know. May be in your *Network* section in the browser – JPG Jun 25 '19 at 14:56
  • @JPG Ahhh I see, you taught me something. The error response is: `{"authors":["This list may not be empty."]}` – user2896120 Jun 25 '19 at 15:03
  • cool.... Can you add more info regarding that ***POST*** request? request payload (from the browser) – JPG Jun 25 '19 at 15:07
  • @JPG `title: dasf desct: dasf content: fdasf authors[]: 1 authors[]: 2` This is how it looks when I do `"authors": [1,2]` – user2896120 Jun 25 '19 at 15:15
  • That's the problem. What about the content type? (browser) – JPG Jun 25 '19 at 15:16
  • @JPG `application/x-www-form-urlencoded; charset=UTF-8` – user2896120 Jun 25 '19 at 15:20
  • specify the `content-type` in your ajax request as `application/json` ref : [this so post](https://stackoverflow.com/questions/18701282/what-is-content-type-and-datatype-in-an-ajax-request) – JPG Jun 25 '19 at 15:25
  • @JPG I did this, and now my error response is: `{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}` and the payload is: `csrfmiddlewaretoken=bmiehYH9PnJrIbXA8TLluoKblrnEnjc6fpYeHMLS0tiH2I8V1jeYh97e0UlbFR43&title=dasf&desct=dasf&content=fdasf&authors%5B%5D=1&authors%5B%5D=2` – user2896120 Jun 25 '19 at 15:31
  • you may need to do JsonStringyfy – JPG Jun 25 '19 at 15:32
  • @JPG Exact same error, but now the payload is: `csrfmiddlewaretoken=bmiehYH9PnJrIbXG8BLluoKblrnEnjc6fpYeHMLS0tiH2I8V1jeYh97e0UlbFR43&title=dasf&desct=dasf&content=fdasf&authors=%5B1%2C2%5D` – user2896120 Jun 25 '19 at 15:34

1 Answers1

-1

check your django settings.py file. You need correct configuration of next parameters to post a request from another server.

 CORS_ORIGIN_WHITELIST = (
    'localhost',
    'your-domain.com',
    '127.0.0.1',
    '127.0.0.1:8080'
)

CSRF_TRUSTED_ORIGINS = (
    'your-domain.com',
)

CORS_ORIGIN_ALLOW_ALL = True

CORS_EXPOSE_HEADERS = [
'Access-Control-Allow-Origin',
'Access-Control-Allow-Headers'
]

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'cache-control',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

I suspect that is because of it