Vue+Django REST framework打造生鲜电商项目:学习过程之报错信息

1.添加精确搜索功能的时候报错:

views.py

from django_filters.rest_framework import DjangoFilterBackend  #精确搜索

class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    '''
    第六版,完美返回JASON数据,代码简洁加强版,加深度定制分页,动态简便绑定http提交方法:router.register(r'goods',views.GoodsListViewSet)
    '''
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination  #分页
    #精确过滤搜索
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('name', 'shop_price',)

settings.py

#精确搜索
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

报错信息:

django.template.exceptions.TemplateDoesNotExist: django_filters/rest_framework/crispy_form.html

原因是教程中没有在setting.py文件中注册:crispt_form

添加该APP后解决问题:

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
    'DjangoUeditor',
    'goods',
    'trade',
    'user_operation',
    'xadmin',
    'crispy_forms',
    #DRF配置
    'rest_framework',
    #精确搜索
    'django_filters',
]

2.Vue项目,单个接口调试的时候

  • 将Vue接口的域名改成本地
    let local_host = 'http://127.0.0.1:8000/';
    
    //获取商品类别信息
    export const getCategory = params => {
      if('id' in params){
        return axios.get(`${local_host}/categorys/`+params.id+'/');
      }
      else {
        return axios.get(`${local_host}/categorys/`, params);
      }
    };

  • 页面报错:
    mock.js:8359 GET http://127.0.0.1:8000//categorys/ net::ERR_CONNECTION_REFUSED

  • 原因:本地服务器没有开启,开启后继续报错:
    Failed to load http://127.0.0.1:8000//categorys/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.

  • 原因:浏览器和服务器不允许跨域
  • 解决办法:设置服务器跨域
  • 安装 pip install django-cors-headers
  • 服务器的settings.py设置APP
        #跨域
        'corsheaders',

  • settings.py
    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',
        ...
    ]
  • 在settings.py的MIDDLEWARE下面添加
    CORS_ORIGIN_ALLOW_ALL = True


  • 解决



你可能感兴趣的:(python,Django)