如何读取文件并将其填入django中的HttpResponse?

时间:2015-12-02 00:37:11

标签: python json django views

我有一个JSON文件,它位于我的django项目文件夹之外,我想阅读它并在我的django项目文件夹中的index.html中使用它。

我在某处读到我可以通过Previous([Work Week])传递文件(我使用[Work Week] [T2Line] 40 1234 41 2345 42 43 3456 作为我的index.html),但我再也找不到它了。

我找到了this,但它没有给出任何解释。任何人都可以向我发送一个关键字或提示,以便在文档中找到它,或者我可以谷歌搜索,我现在有点丢失吗?

提前谢谢!

修改

感谢Chathan Driehuys和this以及this我发现了如何读取JSON并将其加载到字典中。这是我的设置:

views.py

1 个答案:

答案 0 :(得分:1)

我会通过向您正在使用的get_context_data添加CreateView方法来执行此操作。在该方法中,您可以打开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 }}将在模板中提供