【问题标题】:Form POST using TastyPie not json使用 TastyPie 而不是 json 形成 POST
【发布时间】:2013-06-14 09:35:30
【问题描述】:

我在尝试使用 TastyPie POST *form data* 时收到以下错误消息(见下文):

无法解码任何 JSON 对象

我知道我需要在正文中传递一个 json 对象才能使其工作,但是如果我只有表单帖子并且不想使用 json 怎么办(只输出回 json)

如何使用 FORM POST 制作美味的馅饼?

谢谢

class SMSResource(ModelResource):

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

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    确保您的内容类型为 x-www-form-urlencoded 以发帖并尝试:

    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)
    

    然后在你的资源类中:

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

    【讨论】:

      猜你喜欢
      • 2013-11-24
      • 2013-04-16
      • 1970-01-01
      • 2014-08-14
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多