GrantU
GrantU

Reputation: 6555

Form POST using TastyPie not json

I'm getting the following error message (see below) when trying to POST *form data* using TastyPie:

No JSON object could be decoded

I understand that I need to pass a json object in the body for this to work, but what if all I have is form posts and don't want to use json (only output back in json)

How to I make tasty pie work with a FORM POST?

Thanks

class SMSResource(ModelResource):

    class Meta(CommonMeta):
        queryset = Batch.objects.all()
        resource_name = 'sms'
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get']

Upvotes: 1

Views: 608

Answers (1)

Glyn Jackson
Glyn Jackson

Reputation: 8354

Make sure your content type is x-www-form-urlencoded to make a post and try:

class MultipartResource(object):
    def deserialize(self, request, data, format=None):
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/json')

        if format == 'application/x-www-form-urlencoded':
            return request.POST

        if format.startswith('multipart'):
            data = request.POST.copy()
            data.update(request.FILES)
            return data

        return super(MultipartResource, self).deserialize(request, data, format)

    def put_detail(self, request, **kwargs):
        if request.META.get('CONTENT_TYPE').startswith('multipart') and \
                not hasattr(request, '_body'):
            request._body = ''

        return super(MultipartResource, self).put_detail(request, **kwargs)

Then in your resource class:

class SMSResource(MultipartResource, ModelResource):

    class Meta(CommonMeta):
        queryset = Batch.objects.all()
        resource_name = 'sms'
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get']

Upvotes: 3

Related Questions