我有一个django应用程序,我试图将JSON变量形式的gridster小部件配置存储到database.But当我点击我的网页上的“更新”按钮时,我的数据库不存储任何值。
我的JS代码,它将序列值发送到数据库
var gridster;
var $color_picker = $('#color_picker');
var URL = "{% url 'save-grid' %}";
gridster = $(".gridster ul").gridster({
widget_base_dimensions: [80, 80],
widget_margins: [5, 5],
helper: 'clone',
resize: {
enabled: true
}
}).data('gridster');
$(".add-button").on("click", function() {
$('#test').click();
$('#test').on('change', function(e) {
var test = document.getElementById('test');
if (!test) {
alert("Um, couldn't find the fileinput element.");
}
else if (!test.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!test.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = test.files[0];
console.log(file);
fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = function() {
var data = fr.result; // data <-- in this var you have the file data in Base64 format
callbackAddButton(data);
test.value = '';
$('#test').replaceWith($('#test').clone())
};
}
})
});
function callbackAddButton(file) {
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($(`<img src="${file}" height="60px" width="60px">`));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
}
$('.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! :('); }
});
}
});
$('.gridster').on("click", ".delete-button", function() {
gridster.remove_widget($(this).parent());
});
var serialization = updated_grid
serialization = Gridster.sort_by_row_and_col_asc(serialization);
$('.js-seralize-restore').on('click', function () {
gridster.remove_all_widgets();
$.each(serialization, function () {
gridster.add_widget('<li />', this.size_x, this.size_y, this.col, this.row);
});
});
我的urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'myapp/save-grid$', views.save_grid, name='save-grid'),
]
我的views.py
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.shortcuts import render, redirect
from django.utils import timezone
from django.utils.encoding import smart_str
from django.http import HttpResponse
from os import path
from .models import update_grid
def save_grid(request):
if request.method == 'POST':
data = json.loads(request.body)
grid = update_grid(data=data)
grid.save()
return HttpResponse('success') # if everything is OK
我的Models.py
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
class update_grid(models.Model):
title = models.CharField(max_length=255, blank=True)
data = JSONField()
def __str__(self):
return self.title
我能够通过admin添加JSON变量。但是我能够在错误的地方找到
我只是不确定我的javascript部分。我是否已将变量写入django语法正确
修改1
我的JS脚本更新如下
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);
});
现在我收到此错误
POST http://localhost:8000/calendar_grid/save-grid net::ERR_CONNECTION_ABORTED jquery.min.js:2
答案 0 :(得分:0)
我认为问题是你是如何在Django中读取数据的,因为request.body返回一个字节串
尝试替换此javascript行
var data = updated_grid;
与
var data = {json: updated_grid}
然后在你的django视图中通过request.POST这样访问它
def save_grid(request):
if request.method == 'POST':
json_data = request.POST.get('json')
print(json_data) # Can add a print here for testing
data = json.loads(json_data)
grid = update_grid.objects.create(data=data, title='title')
return HttpResponse('success') # if everything is OK
此外,如果您对csrf_token有错误,这有用https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax