提示的是无序对象列表警告,意思是对数据结果进行排序,在views.py中取数据时加入排序即可,默认可以按照id进行排序,示意如下:
classGoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
'''商品列表页,并实现分页、搜索、过滤、排序'''
queryset = Goods.objects.filter(is_delete=False).order_by('id') # 添加根据id排序即可
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filter_class = GoodsFilter
search_fields = ['name','goods_brief','goods_desc']
ordering_fields = ['sold_num','shop_price']
此时再运行,不再显示警告信息。
7.Django Restful framework中使用JWT实现自定义验证{“non_field_errors”:[“无法使用提供的认证信息登录。”]}
先声明小编使用的Django版本为3.0,后面有用。
在DRF中使用验证时经常会使用JSON Web Token进行验证,settings.py配置如下:
# DRF配置REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]}# 自定义用户认证配置AUTHENTICATION_BACKENDS = [
'users.views.CustomBackend',]
apps/users/views.py如下:
from django.db.models import Qfrom django.contrib.auth.backends import ModelBackendfrom django.contrib.auth import get_user_model
User = get_user_model()# Create your views here.classCustomBackend(ModelBackend):
'''自定义用户验证'''
def authenticate(self, username=None, password=None, **kwargs):
try:
print(123)
user = User.objects.get(Q(username=username)|Q(mobile=username))
ifuser.check_password(password)anduser.is_delete != True:
print(456)
returnuser except Exceptionase:
returnNone
urls.py配置如下:
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
# JWT认证路由
url(r'^login/', obtain_jwt_token),]
但是在模拟请求访问时却未收到token,只提示错误信息{"non_field_errors":["无法使用提供的认证信息登录。"]},这让我很苦恼,明明所有配置都没问题啊,百思不得姐,到底哪里出了问题了呢?一直不停的排错、Debug,却还是一样的错误,这让我很郁闷。最后不得不去求助于JWT官方文档,看到环境要求仿佛有点儿感觉了:
Requirements
Python (2.7, 3.3, 3.4, 3.5)
Django (1.8, 1.9, 1.10)
Django REST Framework (3.0, 3.1, 3.2, 3.3, 3.4, 3.5)
这里要求的最高Django版本为1.9,而我自己的Django版本为3.0,凭直觉立马想到会不会是版本不兼容的问题,导致了某些地方不一致。jwt部分就不说了,本身版本没怎么更新,可能问题出在了Django和DRF上面,而最有可能出问题的就是自定义验证类,CustomBackend继承自ModelBackend,于是我到django.contrib.auth.backends源码中查看,其定义如下:
classModelBackend(BaseBackend):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
ifusername is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
ifusername is Noneorpassword is None:
return
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run thedefaultpassword hasher once to reduce the timing
# difference between an existinganda nonexistent user (#20760).
UserModel().set_password(password)
else:
ifuser.check_password(password)andself.user_can_authenticate(user):
returnuser ...
相关阅读 >>
浅析Python打包工具distutils、setuptools
pandas妙招之 在dataframe中通过索引高效获取数据
更多相关阅读请进入《Python》频道 >>

Python编程 从入门到实践 第2版
python入门书籍,非常畅销,超高好评,python官方公认好书。