簡體   English   中英

基於Django類的視圖

[英]Django class based views

網址格式

 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數據,但是我寧願通過始終重定向到當前用戶來捕獲此行為。

嘗試這個:

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