如何读取文件并将其填充到 Django 中的 HttpResponse 中?
How read a file and stuff it into a HttpResponse in django?
我有一个 JSON 文件位于我的 django 项目文件夹之外,我想阅读它并在我的 index.html 中使用它,它位于我的 django 项目文件夹内。
我在某处读到我可以通过 views.py
传递文件(我使用 CreateView
作为我的 index.html),但我找不到了。
我找到了 this 但它没有给出任何解释。任何人都可以向我发送关键字或提示以在文档中找到它,或者我可以 google 因为我现在有点迷路了?
提前致谢!
编辑
感谢 Chathan Driehuys 和 this and this 我找到了如何阅读 JSON 并将其加载到字典中。这是我的设置:
import json
class MyCreateView(CreateView):
def get_context_data(self, **kwargs):
context = super(MyCreateView, self).get_context_data(**kwargs)
with open('/path/to/my/JSON/file/my_json.cfg', 'r') as f:
myfile = json.load(f)
context['my_json'] = my_data
我会通过向您正在使用的 CreateView
添加一个 get_context_data
方法来实现。在该方法中,您可以打开 JSON 文件并解析您需要的数据,然后将其传递给您的视图。
class MyCreateView(CreateView):
def get_context_data(self, **kwargs):
context = super(MyCreateView, self).get_context_data(**kwargs)
with open('my_json_file', 'r') as f:
# parse content from your JSON file and put it in
# the context dictionary
# context['json_item'] = my_val
return context
您的 json_item
将可以通过使用 {{ json_item }}
在模板中使用
我有一个 JSON 文件位于我的 django 项目文件夹之外,我想阅读它并在我的 index.html 中使用它,它位于我的 django 项目文件夹内。
我在某处读到我可以通过 views.py
传递文件(我使用 CreateView
作为我的 index.html),但我找不到了。
我找到了 this 但它没有给出任何解释。任何人都可以向我发送关键字或提示以在文档中找到它,或者我可以 google 因为我现在有点迷路了?
提前致谢!
编辑
感谢 Chathan Driehuys 和 this and this 我找到了如何阅读 JSON 并将其加载到字典中。这是我的设置:
import json
class MyCreateView(CreateView):
def get_context_data(self, **kwargs):
context = super(MyCreateView, self).get_context_data(**kwargs)
with open('/path/to/my/JSON/file/my_json.cfg', 'r') as f:
myfile = json.load(f)
context['my_json'] = my_data
我会通过向您正在使用的 CreateView
添加一个 get_context_data
方法来实现。在该方法中,您可以打开 JSON 文件并解析您需要的数据,然后将其传递给您的视图。
class MyCreateView(CreateView):
def get_context_data(self, **kwargs):
context = super(MyCreateView, self).get_context_data(**kwargs)
with open('my_json_file', 'r') as f:
# parse content from your JSON file and put it in
# the context dictionary
# context['json_item'] = my_val
return context
您的 json_item
将可以通过使用 {{ json_item }}