0

In my app I am trying to save the database data into a JSON file.

Here is my views.py:

if request.POST:
        form = BookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            form.save()

            JSONSerializer = serializers.get_serializer("json")
            json_serializer = JSONSerializer()
            with open("book.json", "w") as out:
                json_serializer.serialize(Book.objects.all(), stream=out)

        return redirect('/index/')
    return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request))

I am using serializer for doing that.
The problem is that the data is saved in the database, but not written to the file.

I am getting the following error,while running the above code

IOError at /addbook/
[Errno 2] No such file or directory: 'fixtures/book.json'
Request Method: POST
Request URL:    http://localhost:8000/addbook/
Django Version: 1.3.7
Exception Type: IOError
Exception Value:    
[Errno 2] No such file or directory: 'fixtures/book.json'
Exception Location: /root/Samples/DemoApp/DemoApp/views.py in addbook, line 53
Python Executable:  /usr/bin/python
Python Version: 2.7.0
4
  • you must put the correct path for book.json Commented Apr 4, 2013 at 9:27
  • Well the code seems to run fine , Could it be a permission issue Commented Apr 4, 2013 at 9:33
  • Catherine,how to set path,as my .json file is in a folder named fixtures inside my app.Can you share me a small idea Commented Apr 4, 2013 at 10:27
  • you can use your settings.PROJECT_ROOT to locate your json file Commented Apr 4, 2013 at 10:40

1 Answer 1

1
path = "{0}/app_name/fixtures/book.json".format(settings.PROJECT_ROOT)
with open(path, "w") as out:
    json_serializer.serialize(Book.objects.all(), stream=out)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.