Package: django-vitevue
Django Vite VueManage Vitejs frontends and compile them to Django static files and templates. FeaturesConfigure Vitejs for Django: use a management
command to help configuring Vitejs to compile to Django templates and static filesTypescript scaffolding: generate Typescript models from existing Django modelsApi and views: api helper frontend class configured for Django and login/logout views with single page app supportInstallpip install django-vitevueAdd"vv",toINSTALLED_APPSMake sure the basic Django template and static dirs settings are present. Run thevvcheckmanagement command to see if the config is okConfiguration of a Vitejs app to compile to Django templates and static filesArchitecture and settingsThe recommended file structure for a single page app is:project_root_dirdjango_projectvite_projectA management command is available to configure some Vitejs frontends compilation options
and commands. First create a frontend in the parent folder of the Django project with a command
like:yarncreatevitefrontend--template=vue-tsOr use and existing one.The root directory can be configured by a setting. By default it is
the parent directory of the Django'sBASE_DIR, like in the file structure shown above.
Example setting to put the frontend dev code directly in the django project directory:VV_BASE_DIR=BASE_DIRGenerate the Vitejs configIf the Vite app project folder is namedfrontendthe command can run without arguments:python {django_project}/manage.py viteconfOtherwise add the app folder name as an argument:python {django_project}/manage.py viteconf --app=my_frontend_app_folder_nameThis command will do the following things:Generate compilation options for thevite.config.jsorvite.config.tsfileGenerate npm build commands forpackage.jsonCheck if all the required npm dependencies are installedThe command runs in dry mode and outputs the config. To write to config files
use the-wflag:python {django_project}/manage.py viteconf -wOptionsConfigure templates and static files destinationThe npmbuildcommand will be configured to output to the Django static file
folder and anindex.htmltemplate. To change these options use these command flags:--template=mytemplate.html: the template to compile to. Relative to the django templates dir--static=myfolder: the static folder to compile assets to. Relative to the first staticfiles dirExample to compile the template totemplates/myapp/mytemplate.htmland the static assets tostatic/myapp:python {django_project}/manage.py viteconf --template=myapp/mytemplate.html --static=myappCompile to a partial templateBy default it will compile a full index page, in single page app mode. It is possible to
compile to a static partial template, without the html tags. Use the partial flag:-p: the template will not have html tags and can be included in a parent Django templateTo configure Vitejs to compile an app in partial mode to a specific template and static folder:python {django_project}/manage.py viteconf -p --app=partialapp --template=mytemplate.html --static=myfolderTypescript modelsGenerate Typescript models from Django modelsThetsmodelscommand can generate Typescript models from Django models:python {django_project}/manage.py tsmodels my_django_appTo write the models to the frontend app:python {django_project}/manage.py tsmodels my_django_app -wExample output:These Django models:classMarket(models.Model):name=models.CharField(max_length=255)classInstrument(models.Model):name=models.CharField(max_length=255)classTrade(models.Model):date=models.DateTimeField()price=models.FloatField()quantity=models.FloatField()market=models.ForeignKey(Market,on_delete=models.CASCADE)instrument=models.ForeignKey(Instrument,on_delete=models.CASCADE)side=models.CharField(max_length=4,choices=SIDE)Output these Typescript models:// Model MarketimportMarketContractfrom"./contract";exportdefaultclassMarket{id:number;name:string;constructor({id,name}:MarketContract){this.id=id;this.name=name}staticfromJson(data:Record<string,any>):Market{returnnewMarket(dataasMarketContract)}}// -------------- Interface --------------exportdefaultinterfaceMarketContract{id:number,name:string,}// Model InstrumentimportInstrumentContractfrom"./contract";exportdefaultclassInstrument{id:number;name:string;constructor({id,name}:InstrumentContract){this.id=id;this.name=name}staticfromJson(data:Record<string,any>):Instrument{returnnewInstrument(dataasInstrumentContract)}}// -------------- Interface --------------exportdefaultinterfaceInstrumentContract{id:number,name:string,}// Model TradeimportMarketContractfrom"../market/contract";importInstrumentContractfrom"../instrument/contract";importTradeContractfrom"./contract";exportdefaultclassTrade{id:number;date:string;price:number;quantity:number;market:MarketContract;instrument:InstrumentContract;side:string;constructor({id,date,price,quantity,market,instrument,side}:TradeContract){this.id=id;this.date=date;this.price=price;this.quantity=quantity;this.market=market;this.instrument=instrument;this.side=side}staticfromJson(data:Record<string,any>):Trade{returnnewTrade(dataasTradeContract)}}// -------------- Interface --------------importMarketContractfrom"../market/contract";importInstrumentContractfrom"../instrument/contract";exportdefaultinterfaceTradeContract{id:number,date:string,price:number,quantity:number,market:MarketContract,instrument:InstrumentContract,side:string,}Add an api to the generated frontend modelsTo scaffold an api for an existing frontend model:python {django_project}/manage.py tsapi my_django_app_nameThis will create an api for the Typescript models and copy anapihelper
in the frontendsrcdirectoryExample outputMethods will be added to models. Ex:exportdefaultclassMarket{// ...staticasyncload(id:number|string):Promise<Market>{constres=awaitapi.get<Record<string,any>>(`/api/market/${id}/`);returnMarket.fromJson(res)}}Login viewsSome login/logout views are available from the backend, and supported by the frontend
api helper class. Add the urls inurls.py:urlpatterns = [
    path("vv/", include("vv.urls")),
		#...
]Two api views will be available:/vv/auth/login/and/vv/auth/logout/. The frontend api
helper class have support for these viewsexample codeExampleExample repository:https://github.com/synw/django-vitevue-exampleRun the testsClone and run:make install
make test-initialTo run the code quality checker installPycheckand run:make quality