Home > Blockchain >  How to access request object of django in react?
How to access request object of django in react?

Time:01-30

I have multiple apps in my Django project but for One app I would like to use react, so I have create two apps one for apis and other for frontend. I used webpack to merge django and react. Now I want to access request.user and user.is_authenticated in my components. How can I access those without calling apis as I am not using token-based authentication so I can not call APIs.

views.py

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

urls.py

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

I would like to use is_authenticated in my sidebar everywhere.

CodePudding user response:

You can just pass the request user and is_authenticated to the context of the index view and access it in your React components via the window object.

In your views.py:

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

In your index.html:

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