django的view实现商品列表页遇到的问题
1、在goods中新增view_base
2、在urls配置
报Object of type datetime is not JSON serializable
错误的原因是json.dumps无法对字典中的datetime时间格式数据进行转化,dumps的原功能是将dict转化为str格式,不支持转化时间,所以需要将json类部分内容重新改写,来处理这种特殊日期格式。
解决方法:
import json import datetime class DateEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') # elif isinstance(obj, date): # return obj.strftime("%Y-%m-%d") else: return json.JSONEncoder.default(self, obj) class GoodsListView(View): def get(self, request): """ 通过django的view实现商品列表页 """ json_list = [] goods = Goods.objects.all()[:10] for good in goods: json_dict = {} json_dict["name"] = good.name json_dict["category"] = good.category.name json_dict["market_price"] = good.market_price json_dict["add_time"] = good.add_time json_list.append(json_dict) from django.http import HttpResponse import json # return HttpResponse(json.dumps(json_list), content_type='application/json') return HttpResponse(json.dumps(json_list, cls=DateEncoder), content_type='application/json')
解决了
添加扩展程序
参考
https://blog.csdn.net/t8116189520/article/details/88657533