之前我们做了一个登陆系统,现在我们再对它进行修改,其实也就是把REST framework融入进去,方便我们看到数据。
首先我们需要载一个叫djangorestframework的包:pip install djangorestframework ,接下来在settings中注册。
INSTALLED_APPS = [
···
'rest_framework',
···
]
在应用文件夹下创建一个serializers.py
这些文件的写法都差不多
"""
mysite/serializers.py
"""
from rest_framework import serializers
from .models import User
class UserSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = '__all__'
__all__:全部属性
编辑views.py
"""
mysite/views.py
"""
···
# rest-------------------------------------------
from rest_framework import viewsets
from .serializers import UserSerializers
class UserViewSet(viewsets.ModelViewSet):
queryset = models.User.objects.all()
serializer_class = UserSerializers
# rest-------------------------------------------
···
之后打开应用文件夹下的urls.py
添加
"""
mysite/urls.py
"""
···
from rest_framework import routers
from . import views
···
···
router=routers.DefaultRouter()
router.register(r'users',views.UserViewSet)
···
urlpatterns = [
···
path('api/userinfo/', include(router.urls)),
path('api/', include('rest_framework.urls', namespace='rest_framework')),
···
]
到这里就结束啦,下面附上效果图
点开链接后:
#--------------------------------------------------------------------------------------------------------------------------
#Ps:出现以下错误: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
在setting中加入:
REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', }
问题一般也就解决了
#--------------------------------------------------------21.7.19------------------------------------------------------------
#Ps:出现以下报错: "Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = '__all__' to the UserSerializers serializer.",
原因:
发现是拼写错误······
将field改成fields即可 #淦