Rookie_123
Rookie_123

Reputation: 2017

Storing JSON variable in django database

In my app that uses Gridster I am changing the widget positions and then saving it as a json variable.I want to store this json variable in django database. For that I am not understanding how should I define a function in views.py and a class in models.py which can store the json variable

My HTML/JS template is

var URL = "{% url 'my_view_url' %}";

   $('.js-seralize-update').on('click', function () {

            var s = gridster.serialize();
            updated_grid=JSON.stringify(s);
            $('#log').val(updated_grid);

            function updategridster(){
            var data = updated_grid;
            $.post(URL, data, function(response){
            if(response === 'success'){ alert('Yay!'); }
            else{ alert('Error! :('); }
    });
}

        });

My views.py

def save_grid(request):
    if request.method == 'POST':

            # Some code to get json variable and store it to model
            return HttpResponse('success') # if everything is OK

I want to write some kind of class in models.py corresponding to view.py so that JSON variable can be saved

Edit1 My models.py is

from django.db import models
from django.utils import timezone
from django.utils import simplejson as json

class update_grid(models.Model):
    data = JSONField(null=True, blank=True)

I just want to send data from views to this model(If it is correct)

Edit 2

My JS Script is updated as follows

  var URL = "{% url 'save-grid' %}";

     $('.js-seralize-update').on('click', function () {

                var s = gridster.serialize();
                updated_grid=JSON.stringify(s);
                $('#log').val(updated_grid);

                function updategridster(updated_grid){
                var data = updated_grid;
                $.post(URL, data, function(response){
                if(response === 'success'){ alert('Yay!'); }
                else{ alert('Error! :('); }
        });
    }
                 updategridster(updated_grid);          
            });

Now I get this error

 POST http://localhost:8000/calendar_grid/save-grid net::ERR_CONNECTION_ABORTED  jquery.min.js:2

Upvotes: 0

Views: 13070

Answers (1)

krs
krs

Reputation: 4154

You have the built in JSONField if you use PostgreSQL.

Otherwise there are several implementations like django-jsonfield, for admin i pair this with django-jsoneditor

Then you can save the JSON data in a single field, and in the case of the built in, you can even do queries/filter on specific keys inside the JSON structure.

Upvotes: 5

Related Questions