Roo*_*123 0 django json django-models django-rest-framework
在我使用 Gridster 的应用程序中,我正在更改小部件位置,然后将其保存为 json 变量。我想将此 json 变量存储在 django 数据库中。为此,我不明白我应该如何在 views.py 中定义一个函数,在 models.py 中定义一个可以存储 json 变量的类
我的 HTML/JS 模板是
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! :('); }
});
}
});
Run Code Online (Sandbox Code Playgroud)
我的意见.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
Run Code Online (Sandbox Code Playgroud)
我想在models.py中写一个对应view.py的类,这样可以保存JSON变量
Edit1 我的 models.py 是
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)
Run Code Online (Sandbox Code Playgroud)
我只想将数据从视图发送到此模型(如果正确)
编辑 2
我的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);
});
Run Code Online (Sandbox Code Playgroud)
现在我收到这个错误
POST http://localhost:8000/calendar_grid/save-grid net::ERR_CONNECTION_ABORTED jquery.min.js:2
Run Code Online (Sandbox Code Playgroud)
如果您使用 PostgreSQL,则您拥有内置的JSONField。
否则有几个实现,如django-jsonfield,对于管理员,我将它与django-jsoneditor 配对
然后您可以将 JSON 数据保存在单个字段中,在内置的情况下,您甚至可以对 JSON 结构内的特定键进行查询/过滤。
| 归档时间: |
|
| 查看次数: |
5945 次 |
| 最近记录: |