xadmin引入django-rest-framework

一、安装:

pip install djangorestframework

安装djangorestframework库

https://github.com/encode/django-rest-framework

GitHub主页

pip install markdown

安装markdown库

 

二、配置demo/settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product.apps.ProductConfig',

'xadmin',
'crispy_forms',
'reversion',
# 添加django-xadmin

'import_export',
# 导入导出

'ckeditor',
'ckeditor_uploader',
# 富文本编辑器

'stdimage',
# django-stdimage

'rest_framework',
# django-rest-framework
]

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 5
# 分页
}

 

三、复制资源文件:

python manage.py collectstatic

拷贝静态文件

此时可看到static目录下新增了static/rest_framework目录

 

四、序列化:

在product目录下面新建product/serializers.py:

from rest_framework import serializers

from product.models import ProductInfo


class ProductInfoSerializer(serializers.HyperlinkedModelSerializer):
# 序列化

class Meta:
model = ProductInfo
fields = (
'id',
'product_name',
'product_picture',
'product_describe',
'product_manager',
'product_detail',
'create_time',
'update_time'
)

五、业务视图product/views.py:

# Create your views here.
from rest_framework import viewsets

from product.models import ProductInfo
from product.serializers import ProductInfoSerializer


class ProductInfoViewSet(viewsets.ModelViewSet):
queryset = ProductInfo.objects.all().order_by('id')
serializer_class = ProductInfoSerializer

 

六、路由demo/urls.py:

import xadmin

from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from rest_framework import routers

from product import views


router = routers.DefaultRouter()
router.register('product_info', views.ProductInfoViewSet)

urlpatterns = [
# path('admin/', admin.site.urls),
path('admin/', xadmin.site.urls),

path('ckeditor/', include('ckeditor_uploader.urls')),
# 添加CKEditor的URL映射

path('api/', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
# 配置django-rest-framwork API路由
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# 配置图片文件url转发

 

 七、API

python manage.py runserver

启动服务

http://127.0.0.1:8000/api/

 

posted @ 2019-08-20 23:31  此生不换Yang  阅读(752)  评论(0编辑  收藏  举报