(生鲜项目)07. api view实现商品列表页
第一步: 环境配置
1. DRF官网: https://www.django-rest-framework.org/
仔细查看自己当前的python版本以及django版本是否支持DRF, 然后就看看哪些支持的模块还没有下载, 由于之前安装过xadmin了, 所以这里正常情况下还有coreapi, pygments, django-guardian没有安装, 在虚拟环境中去安装就行了
注: 如果在安装coreapi的时候报错, 并且提示utf-8 decode错误, 那么就去修改pip的编码格式为gbk(这个暂时放这儿, 我还没遇到过这个错误)
然后 pip uninstall MarkupSafe coreapi , 然后再重新安装
2. 配置与DRF相关的url, 与用APIview写good.view函数
from django.conf.urls import url,include import xadmin from MxShop.settings import MEDIA_ROOT from django.views.static import serve from rest_framework.documentation import include_docs_urls from goods.views_base import GoodsListView urlpatterns = [ url(r'^xadmin/', xadmin.site.urls), url(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}), # 商品列表页 url(r'^goods/$', GoodsListView.as_view(), name="goods-list"), # 生成DRF文档的配置 url(r'^docs/', include_docs_urls(title="慕学生鲜")), # DRF登录配置 url(r'^api-auth/', include('rest_framework.urls')), ]
别忘记注册
INSTALLED_APPS = [ ... 'rest_framework', ]
接着是goods.view
from .serializers import GoodsSerializer from rest_framework.views import APIView from rest_framework.response import Response from .models import Goods # APIview继承了View class GoodsListView(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): goods = Goods.objects.all()[:10] goods_serializer = GoodsSerializer(goods, many=True) # many:是否是querrySet对象 return Response(goods_serializer.data)
最后是 goods.serializers (serializers模块就是起到了Form表单的作用)
from rest_framework import serializers
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=100)
click_num = serializers.IntegerField(default=0)
goods_front_image=serializers.ImageField()
然后配置settings
# 解决 1.11.3版本下使用APIview会报'CSRFCheck' object has no attribute 'process_request'的问题, 这么设置之后, goods的login就不会跳转
所以完美的解决办法是: https://stackoverflow.com/questions/54609495/django-csrfcheck-object-has-no-attribute-process-request
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [] }
最后访问网页
再验证一个goods页面的login能否使用, 我这里出了小BUG, 我登录后能够重定向回这个页面,说明账号密码验证是成功了的
但是重定向回goods页面后,这里仍然显示Log in, 而不是 admin, 看上面 解决 1.11.3版本下使用APIview会报'CSRFCheck' object has no attribute 'process_request'的问题,
----------- over -----------