2

まとめて投稿したいと思います。問題は、各アイテムに画像 (または、場合によっては数枚) が必要なことです。一括リクエストでこれを行うことは可能ですか?

モデル:

class CollageItem(models.Model):
  url = models.URLField(null = True)
  image = models.FileField(upload_to = 'i')
  thumbnail = models.FileField(upload_to = 't')

TastyPie オブジェクト:

class CollageItemResource(ModelResource):
  image = fields.FileField(attribute = 'image', null = True, blank = true)
  thumbnail = fields.FileField(attribute = 'thumbnail', null = True, blank = true)
  class Meta:
    queryset = CollageItem.objects.all(
    resource_name = "collage_item"

一括リクエストを使用して複数の画像を投稿できますか、それとも個々の投稿に戻す必要がありますか?

4

2 に答える 2

0

カスタムシリアライザーロードを使用しました:

class FormPostSerializer(Serializer):
    formats = ['form']
    content_types = {
        'form': 'multipart/form-data',
    }

    def from_form(self, content):
        try:
            dict = cgi.parse_multipart(StringIO(content), self.form_boundary)
        except Exception, e:
            raise e
        for key, value in dict.iteritems():
            dict[key] = value[0] if len(value) > 0 else None
        return dict

複数のファイルを投稿する必要があるすべてのリソースの基本クラス:

class FormResource(ModelResource):
    class Meta:
        serializer = FormPostSerializer()

    def dispatch(self, request_type, request, **kwargs):
        cth = request.META.get('CONTENT_TYPE') or \
            request.META.get('Content-type') or \
            self._meta.serializer.content_types['json']
        self.Meta.serializer.form_boundary = self.parse_content_type_header(cth)
        return super(FormResource, self).dispatch(request_type, request, **kwargs)

    def parse_content_type_header(self, content_type_header):
        parts = cgi.parse_header(content_type_header)
        rv = {}
        for p in parts:
            if isinstance(p, dict):
                rv = dict(rv.items() + p.items())
        return rv

もちろん、シリアライザーには追加の処理が必要です (たとえば、UTF8 フィールド)。回答からそれらを省略しました。

于 2013-08-22T14:20:52.350 に答える