简体   繁体   English

基于Django类的视图

[英]Django class based views

url pattern 网址格式

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

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)

My main view function makes sure logged in users are redirected to their profile page, thus: 我的主视图功能确保已登录的用户被重定向到其个人资料页面,因此:

WEBSITE/users/someuser

Will call to my ProfileView.as_view(), However this still permits users to alter the url to something like: 将调用我的ProfileView.as_view(),但是,这仍然允许用户将url更改为:

WEBSITE/users/someotheruser

Which isn't harmfull because it will still just render the request.user data, but I would rather catch this behaviour by always redirecting to the current user.. I don't really understand how? 这不是有害的,因为它仍然只会呈现request.user数据,但是我宁愿通过始终重定向到当前用户来捕获此行为。

Try this: 尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM