2012-03-31 11 views
1

素晴らしいdjango-tastpieを使用してください。tastypie - POSTでオブジェクトを作成する権限を確認する

私のアプリにはドキュメントという概念があります。文書の所有者は1人で、多くの編集者がいます。編集者はコメントを追加できます。

コメントを投稿できるようになる前に、エディタがドキュメントへのアクセス許可を持っているかどうかを確認したいと思います。しかし、私はどのようにこのチェックをタパスで実行するのか分かりません。 -

# api.py 

class CommentResource(ModelResource): 
    user = fields.ForeignKey(UserResource, 'user') 

    class Meta: 
     queryset = Comment.objects.all() 
     resource_name = 'comments' 
     authorization= DjangoAuthorization() 

     def obj_create(self, bundle, request, **kwargs): 

      # What code can I put here to check if the Editor is in the 
      # EditorGroup 

      return super(AnswerResource, self).obj_create(bundle, request, user=request.user) 

エディタがドキュメントをレビューして、私は私の前に、彼らはEditorGroupの一部であることを確認したいコメントを提出した場合

# models.py 

class Document(models.Model): 
    doc_text = models.TextInput() 
    owner = models.ForeignKey(User) 
    editor_group = models.ForeignKey(EditorGroup) 

class EditorGroup(models.Model): 
    name = models.CharField() 
    user = models.ManyToManyField(User) 

class Comment(models.Model): 
    comment = models.CharField() 
    user = models.ForeignKey() 
    document = models.ForeignKey() 

:ここ

は私のコードは少し単純化します彼らはコメントを作成することができます。

obj_createを使って調べましたが、DocumentオブジェクトにアクセスしてEditor(今はrequest.user)がEditorGroupに含まれているかどうかはわかりません。

obj_createがこのチェックを実行する適切な場所であるかどうかもわかりません。

ご協力いただければ幸いです!ここで

答えて

1

は選択肢の一つである:

​​
+0

ありがとうございました。私はそれを試してみましたが、うまくいきません。Commentオブジェクトがまだ作成されていないためです。 'self.document.editor_group.id'を使用しようとすると、 "error_message"が返されます: "int()引数は文字列か数値で、 'ForeignKey'でなければなりません" – tabdon

+0

yehコメントオブジェクトのコピーについては、bundle.data []を確認してください。 'document_id = bundle.data ['document']' ...のようなものは、何をすべきかを知っておくべきです。 – abolotnov

+0

素晴らしい - 私はコメントオブジェクトのコピーを見ることができます。これで、関連するDocumentインスタンスにアクセスする必要がありますが、私が持っているのはURIです。 URIをオブジェクトインスタンスに変換する方法を知っていますか?私はget_via_uri関数を使ってそれをしようとしましたが、それを取り除くことはできませんでした。 – tabdon

1

あなたはDocumentオブジェクトに何かを確認する必要がある場合には、以下のソリューションはOKらしいです。 RelatedFieldクラスのbuild_related_resourceメソッドを使用してURIからリソースを取得し、それを有効なDjangoオブジェクトにすることができます。しかし、一般的にグループ、パーミッション、認可を確認する必要がある場合は、django-tastypieドキュメントのImplementing Your Own Authentication/Authorizationをよく見てください。

class CommentResource(ModelResource): 

    user = fields.ForeignKey(UserResource, 'user') 
    document = fields.ForeignKey(DocumentResource, 'user') 

    def obj_create(self, bundle, request=None, **kwargs): 
     document_uri = json.loads(request.POST.keys()[0]['document']) 
     document = self.document.build_related_resource(document_uri).obj 
     if request.user.has_permission_to(document) or request.user.is_editor: 
      [...] 
関連する問題