我编写了model.py和views.py.当我从Admin添加json变量时,它会出现以下错误
'update_grid' object has no attribute 'title'
我的views.py
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):
data = JSONField()
def __str__(self):
return self.title
我的JSON变量的格式为
[{"col":1,"row":1,"size_x":1,"size_y":1},{"col":2,"row":1,"size_x":1,"size_y":1},{"col":3,"row":1,"size_x":1,"size_y":1},{"col":4,"row":1,"size_x":1,"size_y":1},{"col":1,"row":2,"size_x":1,"size_y":1},{"col":2,"row":2,"size_x":1,"size_y":1},{"col":3,"row":2,"size_x":1,"size_y":1},{"col":4,"row":2,"size_x":1,"size_y":1},{"col":1,"row":3,"size_x":1,"size_y":1},{"col":2,"row":3,"size_x":1,"size_y":1},{"col":3,"row":3,"size_x":1,"size_y":1},{"col":4,"row":3,"size_x":1,"size_y":1},{"col":5,"row":1,"size_x":1,"size_y":1},{"col":6,"row":1,"size_x":1,"size_y":1}]
答案 0 :(得分:1)
此处的代码使用实例变量title
:
def __str__(self):
return self.title
当Python“查看”你的vars时,它会看到self.title
从未被声明,因此你会收到错误。
要修复它,我会为你的模型添加标题:
class update_grid(models.Model):
title = models.CharField(max_length=30)
data = JSONField()
def __str__(self):
return self.title
我希望它有所帮助