2013-03-27 90 views
0

只是單一對象(細節)我有一個UserResource定義爲:返回,而不是名單

class UserResource(ModelResource): 
    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'user'                              

     # No one is allowed to see all users 
     list_allowed_methods = [] 
     detail_allowed_methods = ['get', 'put', 'patch'] 

     # Hide staff 
     excludes = ('is_staff') 

    def apply_authorization_limits(self, request, object_list): 
     return object_list.filter(pk=request.user.pk) 

    def prepend_urls(self): 
     return [ url(r'^(?P<resource_name>%s)/$' % self._meta.resource_name, self.wrap_view('dispatch_detail'), name='api_dispatch_detail') ] 

我想URI /用戶/只返回當前用戶的詳細信息,沒有列表的。我的解決方案提供了「在此uri中找到多個資源」的錯誤,並且確實也有dispatch_list。我如何擁有/用戶/返回並僅處理當前用戶的詳細信息?

感謝

+0

你說的是在當前登錄用戶的? – 2013-03-27 10:05:53

+0

是的,當前登錄的用戶 – Marin 2013-03-27 12:10:57

回答

1

你應該寫自己的看法環繞tastypie dispatch_detail

class UserResource(ModelResource): 
    [...] 

    def prepend_urls(self): 
    return [ url(r'^(?P<resource_name>%s)/$' % self._meta.resource_name, self.wrap_view('current_user'), name='api_current_user') ] 

    def current_user(self, request, **kwargs): 
    user = getattr(request, 'user', None) 
    if user and not user.is_anonymous(): 
     return self.dispatch_detail(request, pk=str(request.user.id)) 
+0

我意識到這已經很長一段時間了,但我剛剛發現它,它看起來正是我所需要的。但是,我發現這個代碼在認證階段之前運行*,因此它永遠不會超過'is_anonymous()'檢查。有任何想法嗎? – Gabriel 2015-05-14 03:41:54

0

嘗試:

user = get_object_or_404(User, username=username) 
0

爲了使這個對象爲當前登錄的用戶可以從請求對象拉這一點。

user = request.user 

user = User.Objects.get(username=user.username) 

,或利用@gyln

user = get_object_or_404(User, username=user.username) 

顯然,如果你正在做這種方式保證了用戶在視圖驗證答案。

使用object.filter函數將始終返回一個列表,即使只有一個結果;而objects.get方法將只返回一個結果。

+0

我知道如何獲得當前用戶,我不知道如何使列表中的tastypie資源只返回一個對象而不是一個對象列表? – Marin 2013-03-27 12:22:14

相關問題