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
解決