我使用ajax获取get请求,查询数据库,然后(至少应该)返回一个json对象。问题是当我尝试创建json对象时。我收到内部服务器错误500.感谢您的帮助。
视图:
def fabric(request, id):
test = Topics.objects.get(topicId= id)
ids = Topics.objects.get(topic= test)
fabrics = [model_to_dict(fabric) for fabric in Fabrics.objects.filter(fabTopic_id=ids.id)]
print fabrics #prints fabrics string
fabric_list = json.dumps(fabrics)
print "test" #doesn't print
return HttpResponse(fabric_list, content_type='application/json')
印花面料字符串:
[{'fabTopic': 1, 'isPremium': False, 'fabWeave': u'', 'fabImage_secondary': <ProcessedImageFieldFile: avatars/cotton2_1.jpg>, 'fabContent': u'', 'fabName': u'Cotton', 'fabImage': <ProcessedImageFieldFile: avatars/cotton1_1.jpg>, 'fabVideoURL': u'', 'fabDye': u'', 'fabFinish': u'', 'fabVideo': u'', 'fabDescription': u'Cotton is a cellulosic fiber obtained from the seed of a cotton plant Depending on the fiber length and/or finish, fabrics can h', u'id': 1}]
Models.py
from django.db import models
from embed_video.fields import EmbedVideoField
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
class Catagories(models.Model):
catagory = models.CharField(max_length=128)
categoryId = models.CharField(max_length=128)
def __unicode__(self):
return self.catagory
class Topics(models.Model):
fabCatagory = models.ForeignKey(Catagories)
topic = models.CharField(max_length=128)
topicId = models.CharField(max_length=128)
def __unicode__(self):
return self.topic
class Fabrics(models.Model):
fabTopic = models.ForeignKey(Topics)
fabName = models.CharField(max_length=128)
fabContent = models.CharField(max_length=128, blank=True)
fabWeave = models.CharField(max_length=128, blank=True)
fabDye = models.CharField(max_length=128, blank=True)
fabFinish = models.CharField(max_length=128, blank=True)
fabDescription = models.CharField(max_length=8192)
fabImage = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(250, 185)],
format='JPEG',
options={'quality': 60},blank=True)
fabImage_secondary = ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(500, 370)],
format='JPEG',
options={'quality': 60},blank=True)
fabVideo = EmbedVideoField(blank=True)
fabVideoURL = models.URLField(blank=True)
isPremium = models.BooleanField(default=False)
def __unicode__(self):
return self.fabName
答案 0 :(得分:2)
您天真地尝试使用不可序列化的项目序列化dict,例如'fabImage_secondary': <ProcessedImageFieldFile: avatars/cotton2_1.jpg>
。
至少,你想使用一个合适的序列化器:
from django.core import serializers
data = serializers.serialize('json', Fabrics.objects.filter(fabTopic_id=ids.id), fields=('a', 'b'))
有关详细信息,请参阅https://docs.djangoproject.com/en/dev/topics/serialization/。
答案 1 :(得分:1)
在django之外的python脚本中运行json.dumps
并查看错误。
或者只是打开django日志记录以在屏幕上打印错误。
可能json.dumps无法序列化您的Image对象。默认情况下,json.dumps只能序列化和反序列化简单类型,如列表,字符串,数字和字符串。
您必须以序列化程序的某些simpler
形式提供图像,作为文件(字符串)或字节数组的路径(在python2中也是字符串)。