내 게시물 메서드에서 'owner'필드를 현재 사용자 (BasicAuthentication을 사용하고 있습니다)로 자동 채 웁니다. 나는 여기 코드 중 일부를 따랐다 : How to get authorized user object in django-tastypie -하지만 아직 제대로 작동하지 않았다.Django Tastypie - 현재 사용자 자원을 자동으로 선택합니다.
resources.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
그래서이 나타납니다, 하지만 데이터베이스에 아무 것도 추가되지 않고 위치가 잘못 표시됩니다 (끝에/없음/표시).
"bundle.obj.owner = User.objects.get (pk = request.user.id)"행과 관련이 있습니다. 지금까지 내가 bundle.obj.owner 양식에 있어야 말할 수
"error_message": "Cannot assign \"3L\": \"Question.owner\" must be a \"User\" instance."
: 내가 사용하는 경우 "bundle.obj.owner = request.user.id는"그때는 오류 '/ python/mquiz/api/v1/user/3/'- 내 curl 요청에있는 데이터에서 소유자 매개 변수로 이것을 사용하면 (사용자 정의 하이드레이트 메소드를 제거함), 모든 것이 올바르게 작동하고 데이터베이스에 추가됩니다. 그렇다면 사용자 인스턴스를 허용 할 양식으로 변환하려면 어떻게해야합니까?
도움을 주시면 감사하겠습니다.
방금 승인 된 답변으로 업데이트되었습니다. –