一个django应用程序,提供基于类的通用视图和模板标记,使其易于与django视图和模板一起使用react。
django-react-views的Python项目详细描述
django react视图
django react riews是一个django应用程序,它提供了基于类的通用视图和模板标记,使得使用react更加容易 以及django视图和模板。
它可以与channels-redux-python一起使用 以及channels-redux-js来提供一个框架,使用websockets来保存 与数据库状态同步的前端redux状态。
快速启动
将“django_react_views”添加到已安装的应用程序设置中,如下所示:
INSTALLED_APPS=[...'django_react_views',]
在应用程序中创建名为
的目录react
复制
webpack.config.js
或使用您自己的webpack配置,只要它将您的react组件构建到一个静态文件目录中使用npm至少安装
npm install --save-prod react react-dom npm install --save-dev babel-core babel-loader babel-preset-env babel-preset-es2015 babel-preset-react glob webpack webpack-cli
将这些脚本添加到
package.json
"scripts":{"build":"webpack","watch":"webpack --watch"},
执行
npm run watch
开始构建反应文件将react template标记添加到要显示react组件的模板中
{% load react %} ... {% react %} ...
为模板创建视图
fromdjango_react_views.viewsimportReactDetailViewclassMyReactView(ReactDetailView):react_component='MyReactComponent.js'# By default this will resolve to dist/app_name/{react_component}. If {% static %} can not find the file you may need to edit some other properties of this classmodel_serializer=MyModelSerializermodel=MyModel
为视图添加URL
urlpatterns=[...path('my-react-view/<int:pk>/',MyReactView.as_view(),name='my-react-view')]
这个框架提供了window.props,它包含一个javascript对象,可以用来优化您的反应状态。形状为:
window.props={"objects":{"appname.modelname":{"https://example.com/appname/modelname/1/":{objectasserializedbyyourmodelserializer}}}}
启动开发服务器并访问http://127.0.0.1:8000/,然后访问您的页面以查看您正在运行的react组件