2017-06-04 37 views
0

我想在django的listview上使用重定向。如何在django的listview上使用重定向

如果user'name是yusl,他連接到www.photo.com/user/yusl,他可以看到他的照片列表。 ,如果他連接到www.photo.com/user/dksdl,則會讓他重定向www.photo.com/user/yusl。

但有錯誤。錯誤是

TypeError at /user/user/ 
context must be a dict rather than HttpResponseRedirect. 
Request Method: GET 
Request URL: http://ec2-13-124-23-182.ap-northeast-2.compute.amazonaws.com/user/user/ 
Django Version: 1.11.1 
Exception Type: TypeError 
Exception Value:  
context must be a dict rather than HttpResponseRedirect. 
Exception Location: /home/ubuntu/my_env/lib/python3.5/site-packages/django/template/context.py in make_context, line 287 
Python Executable: /home/ubuntu/my_env/bin/python 
Python Version: 3.5.2 
Python Path:  
['/home/ubuntu/project', 
'/home/ubuntu/my_env/lib/python35.zip', 
'/home/ubuntu/my_env/lib/python3.5', 
'/home/ubuntu/my_env/lib/python3.5/plat-x86_64-linux-gnu', 
'/home/ubuntu/my_env/lib/python3.5/lib-dynload', 
'/usr/lib/python3.5', 
'/usr/lib/python3.5/plat-x86_64-linux-gnu', 
'/home/ubuntu/my_env/lib/python3.5/site-packages'] 
Server time: Sun, 4 Jun 2017 17:41:21 +0000 

這是我的views.py

class PhotoListView(ListView): 
    model = Photo 

    def get_context_data(self, **kwargs): 
     username = self.kwargs['username'] 
     User = get_user_model() 
     user = get_object_or_404(User, username=username) 

     if not user == self.request.user: 
      return redirect('index') 

     context = super(PhotoListView, self).get_context_data(**kwargs) 
     context['photo_list'] = user.photo_set.order_by('-posted_on','-pk') 
     return context 

這是urls.py

url(r'^user/(?P<username>[\[email protected]+-]+)/$', PhotoListView.as_view(), name='photo-list'), 

回答

0

不能從get_context_data返回重定向,因爲顧名思義,這是爲了獲取模板上下文。

相反,您需要從實際創建並返回響應的方法中完成;在這種情況下,方法是get

另請注意,您的代碼不必要的複雜:它只需要將用戶名kwarg與當前用戶的用戶名進行比較,根本不需要查詢數據庫。

所以:

class PhotoListView(ListView): 
    model = Photo 

    def get(self, *args, **kwargs): 
     if kwargs['username'] != request.user.username: 
      return redirect('index') 
     return super(PhotoListView, self).get(*args, **kwargs) 
+0

感謝您的諮詢!這對我很有幫助。 –