基于Django类的视图

时间:2011-08-23 12:11:37

标签: python django

url pattern

 url(r'(?P<username>\w+)/$', ProfileView.as_view()),

视图

class ProfileView(TemplateView):
    template_name = "home.html"

    @method_decorator(login_required(login_url='/'))
    def dispatch(self, *args, **kwargs):
        return super(ProfileView, self).dispatch(*args, **kwargs)

我的主视图功能确保登录用户被重定向到他们的个人资料页面,因此:

WEBSITE/users/someuser

将调用我的ProfileView.as_view(),但是这仍然允许用户将URL更改为:

WEBSITE/users/someotheruser

哪个不是有害的,因为它仍然只是呈现request.user数据,但我宁愿通过总是重定向到当前用户来捕获这种行为..我真的不明白怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个:

class ProfileView(TemplateView):
template_name = "home.html"

    @method_decorator(login_required(login_url='/'))
    def dispatch(self, *args, **kwargs):
        if request.user.username == username:
            return super(ProfileView, self).dispatch(*args, **kwargs)
相关问题