如何通过Django上下文创建React应用 [英] 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())
我现在正在尝试将conext(conext = {''foo':'bar'})传递给它.
I'm trying to pass conext (conext = {'foo':'bar'}) to it now.
我尝试通过 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.
是否有更好的方法用Django实现create-react-app或将React代码转换为模板的方法?
Is there a better way to implement create-react-app with django or a way to convert the react code into a template?
推荐答案
我认为答案是将其转换为模板,而不是传递静态文件.
I think the answer is to turn this into a template instead of passing a static file.
settings.MY_VIEW_DIR
是构建的 index.html
的路径,所以我只是将其传递到 settings.py
:
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'})
,并且有效.
这篇关于如何通过Django上下文创建React应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!