0

I will generate a json and save it in a string variable, and I need to save the whole json in my database.

I have a view

class DashboardView(TemplateView):
    template_name = 'votes/dashboard.html'

in this template, I have javascript, and in this javascript I'm generating Json and saving it in a js variable, and I want to put the json in the variable into the DB.

As I'm gonna create a object for the jsons, I'll change templateview to CreateView as It's gonna save.

But how is this json going to become available for the view to be saved ?

7
  • model = Model(json_field=json_data); model.save() Commented Jul 11, 2017 at 14:02
  • @hadi but how do I make javascript save it in the db ? Commented Jul 11, 2017 at 14:03
  • You need to post the json data to a django view, and then use a JsonField to store de data. Commented Jul 11, 2017 at 14:04
  • no , send data via ajax and store it in database Commented Jul 11, 2017 at 14:04
  • docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/… Commented Jul 11, 2017 at 14:04

1 Answer 1

2

brief instruction

using jquery ajax:

$.post( "/your/url/for/store/json/data", { jsonField: jsonData } );

in your view:

def save_json_data(request):
    ...
    data = request.POST.get("jsonField", "")
    model = YourModel(json_field=data)
    model.save()
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the help, Clear up something, this url in $.post, is the url referring to the def save json data ?

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.