Search code examples
djangoreactjsdjango-context

how to pass django context to create react app


I set up create-react-app with django following this example. The webpage get passed in the views like this:

def get(self, request):
        try:
            with open(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f:
                return HttpResponse(f.read())

I'm trying to pass conext (conext = {'foo':'bar'}) to it now.

I tried via get_context_data:

class MyView(DetailView):
    """
    Serves the compiled frontend entry point (only works if you have run `yarn
    run build`).
    """
    def get(self, request):
        try:
            with open(os.path.join(settings.MY_VIEW_DIR, 'build', 'index.html')) as f: 
                return HttpResponse(f.read())
        except FileNotFoundError:
            return HttpResponse(
                """
                This URL is only used when you have built the production
                version of the app. Visit http://localhost:3000/ instead, or
                run `yarn run build` to test the production version.
                """,
                status=501,
            )

    def get_context_data(self, *args, **kwargs):
        context = super(MyView. self).get_context_data(*args, **kwargs)
        context['message'] = 'Hello World!'
        return context

I also tried turning the web page into a template and return

return render(request, 'path/to/my/index.html', {'foo':'bar'})

But that just returns the page without my react code.

Is there a better way to implement create-react-app with django or a way to convert the react code into a template?


Solution

  • I think the answer is to turn this into a template instead of passing a static file.

    settings.MY_VIEW_DIR is the path to the built index.html, so I just passed that into the template loader in the settings.py:

    MY_VIEW_DIR = os.path.join(BASE_DIR, "path","to","my","build","folder")
    
    TEMPLATES = [
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [
                    os.path.join(BASE_DIR, 'templates'),
                    MY_VIEW_DIR
                ],
                'APP_DIRS': True,
                'OPTIONS': {
                    'context_processors': [
                        'django.template.context_processors.debug',
                        'django.template.context_processors.request',
                        'django.contrib.auth.context_processors.auth',
                        'django.contrib.messages.context_processors.messages',
                    ],
                },
            },
        ]
    

    With this i can simply use this in the views:

    def get(self, request):
            return render(request, 'build/index.html', {'foo':'bar'})
    

    and it works.