有人能告訴我如何爲我的視圖編寫像@redirect_to_home
這樣的登錄修飾器,以便它將request.PATH
變量修改爲像/
這樣的新值,並將其應用於視圖。修改請求路徑的視圖的自定義函數修飾器
我已經看到人們用裝飾器做了相當複雜的事情:我還沒有徹底弄懂它們。
感謝
有人能告訴我如何爲我的視圖編寫像@redirect_to_home
這樣的登錄修飾器,以便它將request.PATH
變量修改爲像/
這樣的新值,並將其應用於視圖。修改請求路徑的視圖的自定義函數修飾器
我已經看到人們用裝飾器做了相當複雜的事情:我還沒有徹底弄懂它們。
感謝
感謝彼得對他有用的例子。
def fake_requested_from_root(fn):
"""
Login decorator which when used on a view modifies the reqquest.path
to fool the template into thibking that the request is coming from the
root page
"""
def decorator(request, **kwargs):
request.path = reverse('home')
return fn(request, **kwargs)
return decorator
開始,最好的辦法是瞭解從Django項目登錄裝飾(驗證模塊): http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/decorators.py#L33
如果你看一下「user_passes_test」功能,您將看到如何訪問請求對象。
關於裝飾很好的教程:http://www.ibm.com/developerworks/linux/library/l-cpdecor.html 對於有用裝飾的一些例子看:http://wiki.python.org/moin/PythonDecoratorLibrary