1

I can't manage to make a successful post request to my database, I keep getting post url 403 (Forbidden).

I think it's because of my csrf token since from the admin I can make the post requests without any problem.

My setup is:

Api View:

class ContactFormViewSet(viewsets.ModelViewSet):
    queryset = ContactForm.objects.all()
    serializer_class = ContactFormSerializer

    def post(self): # This returns metrics only for the logged in user
        user_id = self.request.user.id
        return GoogleProperty.objects.filter(user_id=user_id)

Serializer:

class ContactFormSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'google_email',
            'property_name',
            'url',
            'message',
            'created'
        )
        model = ContactForm

My Settings look like this:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':(
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
}

Finally my axios call looks like this:

var url = '/api/v2/messages/'
        let token = document.head.querySelector("[name=_token]").content
        console.log(token)
        axios.post(url,{
          headers: {"X-CSRFToken": token},
          data: {
            google_email:'vm.email',
            property_name:'vm.property',
            url: 'sss',
            message: vm.message,
            xsrfHeaderName: token
          }
        })

And I have a meta tag like this <meta name="_token" content="{{ csrf_token }}">

The token get's print-out fine in my console, I prefer this method because I'm not using jquery.

I've followed this answer/question but it doesn't seem to work for me.

Why my post requests fail?

Costantin
  • 2,486
  • 6
  • 31
  • 48
  • put the csrf token in a hidden input field and then get the value and pass it . – Exprator Jun 02 '17 at 06:25
  • Hi @exprator, thanks for the comment. What would be the difference of taking the token from a hidden input? – Costantin Jun 02 '17 at 12:30
  • Are you logged in when you do that request? Your CSRF_TOKEN setup seems fine. – William R. Marchand Jun 04 '17 at 00:16
  • Yes, I don't know why it's not working this way, but I managed to make it work like this: In my js file: `import axios from 'axios';` `axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";` `axios.defaults.xsrfCookieName = "XCSRF-TOKEN";` And in the settings.py file: `CSRF_COOKIE_NAME = "XCSRF-TOKEN"` – Costantin Jun 04 '17 at 00:33

0 Answers0