簡體   English   中英

如何在反應中訪問django的請求object?

[英]How to access request object of django in react?

我的 Django 項目中有多個應用程序,但對於一個應用程序,我想使用 React,因此我創建了兩個應用程序,一個用於 api,另一個用於前端。 我使用 webpack 合並 django 並做出反應。 現在我想在我的組件中訪問request.useruser.is_authenticated 我如何在不調用 api 的情況下訪問那些,因為我沒有使用基於令牌的身份驗證,所以我無法調用 API。

視圖.py

def index(request):
    return render(request,'index.html')

網址.py

urlpatterns = [
    re_path(r'^(?:.*)/?$',index),
]

我想在我的側邊欄中到處使用 is_authenticated 。

您可以將請求用戶和 is_authenticated 傳遞到索引視圖的上下文,並通過 window object 在您的 React 組件中訪問它。

在你的 views.py 中:

def index(request):
    context = {
        'user': request.user,
        'is_authenticated': request.user.is_authenticated,
    }
    return render(request, 'index.html', context)

在你的 index.html 中:

<script>
  window.user = {{ user|safe }}
  window.is_authenticated = {{ is_authenticated|safe }}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM