如何在django上使用listview重定向
我想在django上的listview中使用重定向 如果用户名是yusl,他连接到www.photo.com/user/yusl,他可以看到他的照片列表。 如果他连接到www.photo.com/user/dksdl,他就会重定向到www.photo.com/user/yusl 但也有错误。错误是如何在django上使用listview重定向,django,listview,redirect,Django,Listview,Redirect,我想在django上的listview中使用重定向 如果用户名是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: GE
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
这是我的观点
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
这是url.py
url(r'^user/(?P<username>[\w.@+-]+)/$', PhotoListView.as_view(), name='photo-list'),
url(r'^user/(?P[\w.@+-]+)/$,PhotoListView.as_view(),name='photo-list'),
您不能从获取上下文数据
返回重定向,因为顾名思义,这是为了获取模板上下文
相反,您需要从实际创建并返回响应的方法执行此操作;在本例中,使用get
方法
还要注意的是,您的代码非常复杂:它只需将用户名kwarg与当前用户的用户名进行比较,根本不需要查询数据库
因此:
您不能从
get\u context\u 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)