使用美妙的django-tastpie。tastypie - 驗證在POST上創建對象的權限
我的應用程序有一個文件的概念(即word文檔)。有一個文件的所有者和許多編輯。編輯可以添加評論。
我想檢查編輯是否有權限文檔,然後纔可以發表評論。但我無法弄清楚如何使用tastpie執行此檢查。
這裏是我的代碼簡化了一下:
# 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()
-
# 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的一部分允許他們創建評論。
我已經研究過使用obj_create,但不確定如何訪問Document對象以查看編輯器(現在是request.user)是否爲EditorGroup的一部分。
也不確定obj_create是否是執行此檢查的正確位置。
任何幫助將不勝感激!
謝謝。我給了一個嘗試,但它不工作,我認爲,因爲Comment對象尚未創建。當我嘗試使用'self.document.editor_group.id'時,我得到一個「error_message」:「int()參數必須是一個字符串或一個數字,而不是'ForeignKey'」 – tabdon 2012-03-31 23:37:16
你好,我愛你看到你在做什麼。檢查你的註釋對象的副本的bundle.data []。就像'document_id = bundle.data ['document']'...從那裏你應該知道該怎麼做。 – abolotnov 2012-04-01 06:31:25
太棒了 - 我可以看到評論對象的副本。現在我需要訪問相關的Document實例,但我擁有的是它的URI。你知道我可以如何將URI轉換爲對象實例嗎?我試圖用get_via_uri函數來做,但一直沒有把它拉下來。 – tabdon 2012-04-01 15:53:20