如何传递 Django 上下文来创建 React 应用程序

how to pass django context to create react app

我按照 this 示例使用 django 设置了 create-react-app。该网页在这样的视图中通过:

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

我正在尝试将 conext (conext = {'foo':'bar'}) 传递给它。

我尝试通过 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

我也试过把网页变成模板然后return

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

但那只是 return 没有我的反应代码的页面。

有没有更好的方法用django实现create-react-app或者将react代码转换成模板的方法?

我认为答案是把它变成一个模板而不是传递一个静态文件。

settings.MY_VIEW_DIR 是构建 index.html 的路径,所以我只是将其传递到 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',
                ],
            },
        },
    ]

有了这个,我可以简单地在视图中使用它:

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

而且有效。