我的商城开发(第五天)—杂项修改

1、修改后台页面显示中文

原有的页面显示都是因为,因为我们在project/settings.py中 LANGUAGE_CODE = 'en-us' 界面效果如下:

这里,修改: LANGUAGE_CODE = 'zh-Hans'

2、商品列表页

2.1 django 自带view实现商品列表页

2.1.1 goods/view_base.py

from  django.views.generic import View
from .models import Goods
from django.http import JsonResponse,HttpResponse
import json

class GoodsListView(View):
    def get(self, request):
        # 通过django的view实现商品列表页
        json_list = []
        # 获取所有商品
        goods = Goods.objects.all()
        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_list.append(json_dict)
        # 返回json
        return HttpResponse(json.dumps(json_list), content_type='application/json')

2.1.2 修改urls.py

# 新增goods/urls.py

from django.conf.urls import url
from .view_base import GoodsListView
app_name = 'goods'

urlpatterns = [
    # 商品列表页面
    url(r'^goods-list/$', GoodsListView.as_view(), name='goods-list')
]


# 修改project/urls.py

from django.conf.urls import url, include
import xadmin

urlpatterns = [
    # path('admin/', admin.site.urls),

    url(r'^xadmin/', xadmin.site.urls),
    url(r'^ueditor/', include('DjangoUeditor.urls')),
    url(r'goods/', include('goods.urls', namespace='goods')),
]

2.1.3 访问并返回结果

2.2 Django的serializer序列化

2.2.1 goods/view_base.py

from django.views.generic import View
from .models import Goods
from django.http import JsonResponse, HttpResponse
import json
from django.core import serializers

class GoodsListView(View):
    def get(self, request):
        # 通过django的view实现商品列表页
        json_list = []
        # 获取所有商品
        goods = Goods.objects.all()

        #
        # 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_list.append(json_dict)
        # # 返回json
        # return HttpResponse(json.dumps(json_list), content_type='application/json')

        json_data = serializers.serialize('json', goods)
        json_data = json.loads(json_data)
        return JsonResponse(json_data,safe=False)

Django serializer虽然很方便,但是我们可以看到有几个局限的地方: 1、字段序列化定死的,要想重组的话非常麻烦 2、从上面截图可以看出来,images保存的是一个相对路径,我们还需要补全路径,而这些drf都可以帮助我们做到

接下来,我们介绍下使用django-rest-framework,做后台API开发


评论(0 ) 点赞(19)


暂未登录,请登录之后发表评论。 QQ