【问题标题】:how to pass django context to create react app如何传递 django 上下文来创建反应应用程序
【发布时间】:2019-03-05 23:01:12
【问题描述】:

我按照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 render(request, 'path/to/my/index.html', {'foo':'bar'})

但这只是返回没有我的反应代码的页面。

有没有更好的方法来使用 django 实现 create-react-app 或将反应代码转换为模板?

【问题讨论】:

    标签: django reactjs django-context


    【解决方案1】:

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

    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'})
    

    它有效。

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多