Package: inertia-django
Inertia.js Django AdapterInstallationBackendInstall the following python package via pippipinstallinertia-djangoAdd the Inertia app to yourINSTALLED_APPSinsettings.pyINSTALLED_APPS=[# django apps,'inertia',# your project's apps,]Add the Inertia middleware to yourMIDDLEWAREinsettings.pyMIDDLEWARE=[# django middleware,'inertia.middleware.InertiaMiddleware',# your project's middleware,]Finally, create a layout which exposes{% block inertia %}{% endblock %}in the body and set the path to this layout asINERTIA_LAYOUTin yoursettings.pyfile.Now you're all set!FrontendDjango specific frontend docs coming soon. For now, we recommend installingdjango_viteand following the commits on the Django Viteexample repo. Once Vite is setup with
your frontend of choice, just replace the contents ofentry.jswiththis file (example in react)You can also check out the official Inertia docs athttps://inertiajs.com/.CSRFDjango's CSRF tokens are tightly coupled with rendering templates so Inertia Django automatically handles adding the CSRF cookie for you to each Inertia response. Because the default names Django users for the CSRF headers don't match Axios (the Javascript request library Inertia uses), we'll need to either modify Axios's defaults OR Django's settings.You only need to choose one of the following options, just pick whichever makes the most sense to you!In yourentry.jsfileaxios.defaults.xsrfHeaderName="X-CSRFToken"axios.defaults.xsrfCookieName="csrftoken"ORIn your Djangosettings.pyfileCSRF_HEADER_NAME='HTTP_X_XSRF_TOKEN'CSRF_COOKIE_NAME='XSRF-TOKEN'UsageResponsesRender Inertia responses is simple, you can either use the provided inertia render function or, for the most common use case, the inertia decorator. The render function accepts four arguments, the first is your request object. The second is the name of the component you want to render from within your pages directory (without extension). The third argument is a dict ofpropsthat should be provided to your components. The final argument istemplate_data, for any variables you want to provide to your template, but this is much less common.frominertiaimportrenderfrom.modelsimportEventdefindex(request):returnrender(request,'Event/Index',props={'events':Event.objects.all()})Or use the simpler decorator for the most common use casesfrominertiaimportinertiafrom.modelsimportEvent@inertia('Event/Index')defindex(request):return{'events':Event.objects.all(),}Shared DataIf you have data that you want to be provided as a prop to every component (a common use-case is information about the authenticated user) you can use thesharemethod. A common place to put this would be in some custom middleware.frominertiaimportsharefromdjango.confimportsettingsfrom.modelsimportUserdefinertia_share(get_response):defmiddleware(request):share(request,app_name=settings.APP_NAME,user_count=lambda:User.objects.count(),# evaluated lazily at render timeuser=lambda:request.user,# evaluated lazily at render time)returnget_response(request)returnmiddlewareLazy PropsOn the front end, Inertia supports the concept of "partial reloads" where only the props requested
are returned by the server. Sometimes, you may want to use this flow to avoid processing a particularly slow prop on the intial load. In this case, you can useLazy props. Lazy props aren't evaluated unless they're specifically requested by name in a partial reload.frominertiaimportlazy,inertia@inertia('ExampleComponent')defexample(request):return{'name':lambda:'Brandon',# this will be rendered on the first load as usual'data':lazy(lambda:some_long_calculation()),# this will only be run when specifically requested by partial props and WILL NOT be included on the initial load}Json EncodingInertia Django ships with a custom JsonEncoder atinertia.utils.InertiaJsonEncoderthat extends Django'sDjangoJSONEncoderwith additional logic to handle encoding models and Querysets. If you have other json
encoding logic you'd prefer, you can set a new JsonEncoder via the settings.SSRBackendEnable SSR via theINERTIA_SSR_URLandINERTIA_SSR_ENABLEDsettingsFrontendComing Soon!SettingsInertia Django has a few different settings options that can be set from within your project'ssettings.pyfile. Some of them have defaults.The default config is shown belowINERTIA_VERSION='1.0'# defaults to '1.0'INERTIA_LAYOUT='layout.html'# required and has no defaultINERTIA_JSON_ENCODER=CustomJsonEncoder# defaults to inertia.utils.InertiaJsonEncoderINERTIA_SSR_URL='http://localhost:13714'# defaults to http://localhost:13714INERTIA_SSR_ENABLED=False# defaults to FalseTestingInertia Django ships with a custom TestCase to give you some nice helper methods and assertions.
To use it, just make sure your TestCase inherits fromInertiaTestCase.InertiaTestCaseinherits from Django'sdjango.test.TestCaseso it includes transaction support and a client.frominertia.testimportInertiaTestCaseclassExampleTestCase(InertiaTestCase):deftest_show_assertions(self):self.client.get('/events/')# check the componentself.assertComponentUsed('Event/Index')# access the component nameself.assertEqual(self.component(),'Event/Index')# props (including shared props)self.assertHasExactProps({name:'Brandon',sport:'hockey'})self.assertIncludesProps({sport:'hockey'})# access propsself.assertEquals(self.props()['name'],'Brandon')# template dataself.assertHasExactTemplateData({name:'Brian',sport:'basketball'})self.assertIncludesTemplateData({sport:'basketball'})# access template dataself.assertEquals(self.template_data()['name'],'Brian')The inertia test helper also includes a specialinertiaclient that pre-sets the inertia headers
for you to simulate an inertia response. You can access and use it just like the normal client with commands likeself.inertia.get('/events/'). When using the inertia client, inertia custom assertionsare notenabled though, so only use it if you want to directly assert against the json response.ExamplesDjango Svelte Template- A Django template and example project demonstrating Inertia with Svelte and SSR.Thank youA huge thank you to the community members who have worked on InertiaJS for Django before us. Parts of this repo were particularly inspired byAndres VargasandSamuel Girardin. Additional thanks to Andres for the Pypi project.Maintained and sponsored by the team atbellaWatt