-1

I have a JSON file that lives outside my django project folder and I want to read it and use it in my index.html which is inside my django project folder.

I read somewhere that I can pass files through views.py (I am using CreateView as my index.html), but I can't find it anymore.

I found this but it doesn't give any explanation. Can anyone send me a keyword or a hint to find it in the documentation or I can google for, I'm kind of lost right now?

Thanjks in advance!

EDIT

Thanks to Chathan Driehuys and this and this I found out how to read a JSON and load it into the dictionary. Here's my setup:

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
Community
  • 1
  • 1
Tom
  • 2,545
  • 5
  • 31
  • 71
  • 1
    What do you mean by "read it an use it in my index.html"? Are you trying to render the data in the JSON file or are you trying to read the contents of the JSON file and use it to do something else in code? – Jkk.jonah Dec 02 '15 at 02:21
  • I am trying to use the content of the JSON file and use it to do something else in my javascript code – Tom Dec 02 '15 at 15:59

1 Answers1

1

I would do this by adding a get_context_data method to the CreateView you are using. In the method you could open the JSON file and parse the data you need, then pass it to your view.

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

Your json_item would then be available in a template by using {{ json_item }}

Chathan Driehuys
  • 1,173
  • 3
  • 14
  • 28
  • awesome thanks, this was what I was looking for, now I only have to figure out how the syntax works, thank you so much! – Tom Dec 02 '15 at 17:21