在视图中使用tastypie资源时出错

时间:2013-05-24 08:30:45

标签: django view resources tastypie

这是我的资源:

class ImageResource(ModelResource):
     album = fields.ForeignKey(AlbumResource, 'album')
     upload_by = fields.ForeignKey(UserResource, 'upload_by')


     class Meta:
         always_return_data=True
         filtering = {
                     "album": ('exact',),
                      }
    queryset = Image.objects.all()
    cache = SimpleCache(timeout=100)
    resource_name = 'image'
    authorization = ImageAuthorization()

class ImageAuthorization(Authorization):
    def read_list(self, object_list, bundle):
         # This assumes a ``QuerySet`` from ``ModelResource``.
         userprofile = UserProfile.objects.get(user = bundle.request.user)
         album = Album.objects.filter(family=userprofile.family)
         return object_list.filter(album__in=album)

当我尝试在视图中使用ImageResource时:

 @csrf_exempt
def upload(request):
    if request.method == 'POST':
       if request.FILES:
            uploadedfile = request.FILES
            file = uploadedfile['item']
            album = Album.objects.get(pk=int(request.POST['album_id']))
            img = Image(
                album = album,
                name = file.name,
                src=file,
                upload_by = request.user,
                )
            # img.save()

            ir = ImageResource()
            uploaded_img = ir.obj_get(src=file)
            print uploaded_img


    return HttpResponse('True')

这总是会引起错误

obj_get() takes exactly 2 arguments (1 given)

我的代码有什么问题???以及如何获得刚刚上传的图片的资源

1 个答案:

答案 0 :(得分:2)

您为什么要创建ImageResource的实例?这毫无意义。

obj_get是tastypie资源的一种方法,它是资源流程图的一部分。它需要一个bundle对象。

obj_get(self, bundle, **kwargs): ...

您不必为上传的每个图像动态创建资源,甚至不需要实例化一个资源,因为url模块会为您执行此操作。

我建议您重新阅读documentation并相应注册ImageResource和/或AlbumResource。这些资源将在register the resources to your urls module之后自动提取上传的图片或相册。