小编Ale*_*nes的帖子

Django DetailView - 如何更改get_object以检查字段

所以我想做一个DetailView单独显示照片及其相关信息.但是,我想让它确保用户也有权访问照片.

这是视图的urls.py

url(r'^photo/(?P<slug>[\-\d\w]+)/$', views.PhotoDetail.as_view(), name='photo'),
Run Code Online (Sandbox Code Playgroud)

这是views.py

class PhotoDetail(DetailView):
    template_name = 'otologue/photo_detail.html'

    def get_object(self, queryset=None):
        slug = self.get_slug_field()
        print(slug)
        object_instance = Photo.objects.filter(slug=slug)
        print(object_instance)
        object_user = object_instance.photoextended.user
        user = get_object_or_404(User, username=self.request.user)  # Get the user in the view

        if object_user != user:  # See if the object_user is the same as the user
            return HttpResponseForbidden('Permission Error')

        else:
            return object_instance
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样我尝试get_slug_field()但是当我打印它时它只会说'slug'当slug应该说出url中的对象slug.从这里,object_instance没有任何对象,然后为什么我试图从中获取用户,它找不到任何数据.

python django django-views django-class-based-views

5
推荐指数
1
解决办法
1万
查看次数