在我的发布方法中,我想用当前用户自动填充“所有者”字段(我使用的是 BasicAuthentication)。我在这里遵循了一些代码:How to get authorized user object in django-tastypie - 但我还没有完全让它正常工作。
资源.py:
class QuestionResource(ModelResource):
owner = fields.ForeignKey(UserResource, 'owner')
class Meta:
queryset = Question.objects.all()
allowed_methods = ['get','post']
fields = ['title','type']
resource_name = 'question'
include_resource_uri = True
serializer = PrettyJSONSerializer()
authentication = BasicAuthentication()
authorization = Authorization()
def obj_create(self, bundle, request=None, **kwargs):
bundle = self.full_hydrate(bundle, request)
return bundle
def obj_update(self, bundle, request=None, **kwargs):
bundle = self.full_hydrate(bundle, request)
return bundle
def full_hydrate(self, bundle, request=None):
bundle = self.hydrate(bundle, request)
return bundle
def hydrate(self, bundle, request=None):
bundle.obj.owner = User.objects.get(pk = request.user.id)
return bundle
如果我发出以下内容:
curl -u USERNAME:XXXXXXX --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"title\":\"my new question\",\"type\":\"multichoice\"}" http://localhost/python/mquiz/api/v1/question/
我得到回应:
HTTP/1.1 201 CREATED
Date: Fri, 02 Nov 2012 08:28:05 GMT
Server: Apache/2.2.22 (Ubuntu)
Vary: Accept-Language,Cookie,Accept-Encoding
Location: http://localhost/python/mquiz/api/v1/question/None/
Content-Language: en-us
Content-Length: 0
Content-Type: text/html; charset=utf-8
所以看起来好像一切正常,但没有任何内容添加到数据库中,并且位置看起来错误(最后是 /None/)。
我确定这与“bundle.obj.owner = User.objects.get(pk = request.user.id)”行有关。如果我使用“bundle.obj.owner = request.user.id”,则会收到错误消息:
"error_message": "Cannot assign \"3L\": \"Question.owner\" must be a \"User\" instance."
据我所知,bundle.obj.owner 需要采用以下形式:'/python/mquiz/api/v1/user/3/' - 如果我在 curl 请求中的数据中使用它作为所有者参数(并删除我的自定义水合物方法),然后一切正常并添加到数据库中。那么如何将我的 User 实例转换为可以接受的形式呢?
非常感谢任何帮助。