用于惯性.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.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以获取如何使用此软件包的示例。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java奇怪的排序行为   使用按偏移量移动时,java移动目标超出边界异常   java如何在redis中为SSO刷新令牌的过期时间?   java错误:未加载Servlet Jar。。。有问题的类:javax/servlet/servlet。班   java二进制筛选器失败:价格\u筛选器   java如何在JLabel中使ImageIcon的背景透明   java中的日期分析异常   使用Java递归打印小数字列表的子集   java如何修改此真值表,使其使用并显示1和0,而不是true和false   java在ApacheKafka中,如何使用条件消息发布来支持乐观并发   Java发现了可能带来安全风险的应用程序组件   通过Java从终端运行R   使用TomcatDBCP的java JDBC需要Tomcat自己的/lib中的JDBC驱动程序   java使用枚举集   使用API 23 安卓的java特定错误导航视图   java Spring Boot+Hibernate,使用@RequestBody对POST请求进行不正确的解析