用于惯性.js的django适配器。
inertia-django的Python项目详细描述
Inertia.js django适配器
Warning: This project is in a very early stage and depends on another early stage library and its frontend adapters called Inertia.js.
要求
这个包应该在django应用程序中使用,它使用django-rest-framework的序列化器。
$ pipenv install django djangorestframework django-webpack-loader
安装
使用Inertia Django仍有许多手动步骤。我正在寻找使初始设置更顺利的方法(和帮助的人)。
从PyPI:
安装惯性django包$ pipenv install inertia-django
网页包
INFO: For now it might be the easiest to take a look or clone the example repository.
你必须为Dynamic Imports Feature使用webpack。以下配置是从Django Inertia.js Example中借用的。它使用了一些不需要的插件,如purgecss、tailwind、minicssextract等,但重要的是:
- Webpack Bundle Tracker用于Django Webpack Loader。
- Vue Loader是可选的,但目前只有inertia-vue适配器。
webpack.config.js:
constpath=require("path");constBundleTracker=require('webpack-bundle-tracker');constVueLoaderPlugin=require('vue-loader/lib/plugin');constCleanWebpackPlugin=require('clean-webpack-plugin');constglob=require("glob-all");constMiniCssExtractPlugin=require('mini-css-extract-plugin');constPurgecssPlugin=require("purgecss-webpack-plugin");classTailwindExtractor{staticextract(content){returncontent.match(/[A-Za-z0-9-_:\/]+/g)||[];}}module.exports={mode:'development',devtool:'inline-source-map',// TODO: adjust the entry points to your projectentry:["./core/assets/js/index.js","./core/assets/css/index.postcss"],output:{publicPath:"/static/bundles/",filename:"[name]-[hash].js",chunkFilename:'[name]-[hash].js',path:path.resolve('./bundles/'),},plugins:[newBundleTracker({filename:'./webpack-stats.json'}),newVueLoaderPlugin(),newCleanWebpackPlugin(),newMiniCssExtractPlugin({filename:"[name]-[hash].css"}),newPurgecssPlugin({paths:glob.sync([// TODO: adjust the directories to your projectpath.join(__dirname,"core/assets/js/**/*.vue"),path.join(__dirname,"core/templates/index.html")]),extractors:[{extractor:TailwindExtractor,extensions:["html","js","vue"]}]})],module:{rules:[{test:/\.m?js$/,exclude:/(node_modules|bower_components)/,use:{loader:'babel-loader',options:{presets:['@babel/preset-env'],plugins:["@babel/plugin-syntax-dynamic-import"]}}},{test:/\.vue$/,use:'vue-loader'},{test:/\.postcss$/,use:[{loader:MiniCssExtractPlugin.loader,},{loader:'css-loader',options:{importLoaders:1}},'postcss-loader',]}]},resolve:{extensions:['.js','.vue'],alias:{'vue$':'vue/dist/vue.runtime.js',// TODO: adjust or remove, it's a convenient way to import js files in your components'@':path.resolve('core/assets/js'),}},}
用法
render_inertia
函数
使用惯性django呈现vue组件的最简单方法是使用render_inertia
函数。注意:您的项目中必须有一个Index.vue
组件。
frominertiaimportrender_inertiadefindex(request):# for function views just use the render_inertia functionreturnrender_inertia(request,'Index',props={'title':'My inertia-django page'},template_name='index.html')
每次写这个都有点麻烦,所以您可以省略template_name
,并在settings.py:
INERTIA_TEMPLATE='index.html'
之后,您只需拨打电话:
frominertiaimportrender_inertiadefindex(request):# for function views just use the render_inertia functionreturnrender_inertia(request,'Index',props={'title':'My inertia-django page'})
InertiaListView
惯性django附带了泛型ListView:
视图.py:
classIndex(InertiaListView):# Inertia supports List and DetailViews right nowmodel=Contactserializer_class=ContactSerializercomponent_name="Index"
index.vue
<template> <Layout> <h2 class="mb-4">Contacts</h2> <p>User: {{shared.user.username}}</p> <ul> <li :key="contact.id" v-for="contact in contact_list"> <inertia-link :href="'/contact/' + contact.id"> {{contact.name}} </inertia-link> </li> </ul> </Layout> </template> <script> import { InertiaLink } from "inertia-vue"; import Layout from "@/Components/Layout"; export default { props: ["contact_list", "shared"], components: { Layout, InertiaLink } }; </script>
InertiaDetailView
惯性django附带了泛型DetailView:
视图.py:
classContactView(InertiaDetailView):model=Contactserializer_class=ContactSerializercomponent_name="Contact"props={"test":True}# you can inject any props you want
contact.vue:
<template> <Layout> <inertia-link href="/">Home</inertia-link> <h2 class="mb-4">{{contact.name}}, {{contact.first_name}}</h2> <p>Age: {{contact.age}}</p> <p>Test: {{test}}</p> </Layout> </template> <script> import { InertiaLink } from "inertia-vue"; import Layout from "@/Components/Layout"; export default { props: ['contact', 'test'], components: { Layout, InertiaLink } }; </script>
inertia.share
函数
如果你想有一些基本的道具总是被注入,你可以在组件之间share
它们:
I had to declare the
UserSerializer
in apps.py so that it is available at startup. If somebody has a better idea feel free to create an issue.
例如apps.py:
fromdjango.appsimportAppConfigfromdjango.contrib.authimportget_user,get_user_modelfromrest_frameworkimportserializersfrominertiaimportsharedefcurrent_user(request):classUserSerializer(serializers.ModelSerializer):classMeta:model=get_user_model()fields=["username","email"]returnUserSerializer(get_user(request)).dataclassCoreConfig(AppConfig):name='core'defready(self):share('title','Django Inertia.js Example ?')share('user',current_user)
您可能已经认识到current_user
是一个函数。当呈现惯性django时,检查共享属性是否可调用,如果可以调用,它将使用当前请求调用该函数。
示例
查看this repository以获取如何使用此软件包的示例。