{"id":13724304,"url":"https://github.com/torchbox/storybook-django","last_synced_at":"2025-04-09T20:09:15.531Z","repository":{"id":48792562,"uuid":"242189814","full_name":"torchbox/storybook-django","owner":"torchbox","description":"Develop Django UI components in isolation, with Storybook","archived":false,"fork":false,"pushed_at":"2025-04-08T21:45:08.000Z","size":3136,"stargazers_count":110,"open_issues_count":4,"forks_count":9,"subscribers_count":20,"default_branch":"main","last_synced_at":"2025-04-09T20:09:10.213Z","etag":null,"topics":["django","pattern-library","storybook","storybook-addon","storyshots"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/torchbox.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"docs/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"docs/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-02-21T17:03:53.000Z","updated_at":"2025-04-08T21:45:11.000Z","dependencies_parsed_at":"2024-01-11T19:17:13.378Z","dependency_job_id":"9c208ea8-c3f9-4b0c-9cf1-b1ec01ff0399","html_url":"https://github.com/torchbox/storybook-django","commit_stats":{"total_commits":133,"total_committers":2,"mean_commits":66.5,"dds":0.007518796992481258,"last_synced_commit":"93a870ef068b420c7a432aba21c31f2fb8643528"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torchbox%2Fstorybook-django","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torchbox%2Fstorybook-django/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torchbox%2Fstorybook-django/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torchbox%2Fstorybook-django/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/torchbox","download_url":"https://codeload.github.com/torchbox/storybook-django/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248103872,"owners_count":21048245,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","pattern-library","storybook","storybook-addon","storyshots"],"created_at":"2024-08-03T01:01:54.117Z","updated_at":"2025-04-09T20:09:15.506Z","avatar_url":"https://github.com/torchbox.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Third-Party Packages"],"sub_categories":["Testing"],"readme":"# Storybook for Django \u003cimg src=\"https://raw.githubusercontent.com/torchbox/storybook-django/main/.github/storybook-django-logo.svg?sanitize=true\" alt=\"\" width=\"90\" height=\"90\" align=\"right\"\u003e\n\n[![npm](https://img.shields.io/npm/v/storybook-django.svg)](https://www.npmjs.com/package/storybook-django) [![Build status](https://github.com/torchbox/storybook-django/workflows/CI/badge.svg)](https://github.com/torchbox/storybook-django/actions)\n\nStorybook for Django is an experimental UI development environment for Django components. It allows you to implement, document, and test UI components in isolation from your Django views.\n\n![Screenshot of the Storybook UI, with a Django UI component displaying](.github/storybook-django-screenshot.png)\n\n## How it works\n\nServer-side, this uses [django-pattern-library](https://github.com/torchbox/django-pattern-library) to mock template context and template tags. Client-side, we use [Storybook](https://storybook.js.org/) to create stories from our templates.\n\n## Getting started\n\nLet’s get you set up. There are two requirements:\n\n1. First, start by setting up [django-pattern-library](https://github.com/torchbox/django-pattern-library), v0.7.0 and up. Have a look at our [demo settings.py](https://github.com/torchbox/storybook-django/blob/main/demo/settings.py) as an example.\n2. Then, set up [Storybook](https://storybook.js.org/). We expect `storybook-django` to work with any framework supported by Storybook, and provide built-in support for React (Vue in progress).\n\nNext, install our package:\n\n```sh\nnpm install --save-dev storybook-django\n```\n\n### Middleware\n\nAdd a `middleware.js` inside your Storybook configuration folder (`.storybook` by default):\n\n```js\nconst {\n  createDjangoAPIMiddleware,\n} = require('storybook-django/src/middleware');\n\nmodule.exports = createDjangoAPIMiddleware({\n  // Point this at your Django runserver instance, with the correct port number.\n  origin: 'http://localhost:8001',\n  apiPath: ['/pattern-library/'],\n});\n```\n\nThis will forward pattern library API requests to Django. You may optionally add more API path patterns to `apiPath` to make other requests to your Django backend.\n\n### Optional Webpack configuration\n\nThis is optional but highly recommended. To leverage Storybook’s live-reloading and documentation capabilities, we need to configure it to load our templates. Edit your Storybook `main.js` file to customise the `webpackFinal` option:\n\n```js\nmodule.exports = {\n  webpackFinal: (config) =\u003e {\n    config.module.rules = config.module.rules.concat([\n      {\n        test: /\\.html$/,\n        // Webpack 5:\n        type: 'asset/source',\n        // Webpack 4 (make sure to also install the raw-loader package):\n        // use: 'raw-loader',\n      },\n    ]);\n\n    return config;\n  }\n```\n\n### React usage\n\nHere is the most basic story for a Django template:\n\n```js\nimport { Pattern } from 'storybook-django/src/react';\n\nexport default {};\n\nexport const Base = () =\u003e (\n  \u003cPattern\n    template=\"patterns/components/streamfield/heading_block.html\"\n    context={{ value: 'An important section' }}\n  /\u003e\n);\n```\n\n`Pattern` uses a hard-coded `endpoint` of `/pattern-library/api/v1/render-pattern` by default. To change this, pass a different value. For example,\n\n```js\n\u003cPattern endpoint=\"/storybook-patterns/api/v1/render-pattern\" /\u003e\n```\n\nIf this is a necessity for your project, consider creating your own wrapper for the `Pattern` component rather than having to define the `endpoint` in all stories.\n\n#### With auto-generated template paths\n\nOur `Pattern` component has to be told which `template` to render, Alternatively, we can use [Webpack’s `__filename`](https://webpack.js.org/api/module-variables/#__filename-nodejs) support to auto-generate the template path. First, configure Webpack:\n\n```js\nconfig.node = {\n  __filename: true,\n};\n```\n\nThen, use the `filename` prop instead of `template`:\n\n```js\n\u003cPattern filename={__filename} /\u003e\n```\n\nThis `filename` prop assumes the template is in the same folder as the template, with the same file name except for the extension (replaces `.stories.(js|tsx)` with `.html`).\n\n#### With Storybook features\n\nAnd here is a more advanced examples, showcasing different Storybook features:\n\n- Setting a custom title for the story.\n- Loading Markdown files to use as documentation.\n- Loading the component’s template to display alongside the docs, and for live-reloading.\n- Setting up [controls](https://storybook.js.org/docs/react/essentials/controls).\n- Having multiple stories with different data.\n\n```js\nimport { Pattern } from 'storybook-django/src/react';\n\nimport docs from './quote_block.md';\nimport template from './quote_block.html';\n\nexport default {\n  title: 'Components / quote_block',\n  parameters: {\n    docs: {\n      source: { code: template },\n      extractComponentDescription: () =\u003e docs,\n    },\n  },\n  argTypes: {\n    quote: {\n      control: { type: 'text' },\n      description: 'Will be displayed first',\n    },\n    attribution: {\n      control: { type: 'text' },\n      description: 'Underneath the quote (optional)',\n    },\n  },\n};\n\nexport const Base = (args) =\u003e (\n  \u003cPattern filename={__filename} context={{ value: args }} /\u003e\n);\n\nBase.args = {\n  quote: 'Someone believed in me once and now it’s time for me to do the same.',\n  attribution: 'Young person',\n};\n\nexport const NoAttribution = Base.bind({});\n\nNoAttribution.args = {\n  quote: Base.args.quote,\n  attribution: null,\n};\n```\n\n#### Making the most of React\n\nThe point of using React is to be able to fully customise the context within which our Django components are displayed. Here is an example, with a simple SVG icon template:\n\n```js\nconst IconPattern = (props) =\u003e (\n  \u003cPattern\n    element=\"span\"\n    template=\"patterns/components/icon/icon.html\"\n    context={props}\n  /\u003e\n);\n\nexport const ReactDemoStory = () =\u003e (\n  \u003cspan\u003e\n    \u003ca href=\"https://www.example.com\"\u003e\n      View our complete guide \u003cIconPattern name=\"arrow\" /\u003e\n    \u003c/a\u003e\n  \u003c/span\u003e\n);\n```\n\n### Vue usage\n\nWe are working on Vue support. Please refer to [Usage with Vue #7](https://github.com/torchbox/storybook-django/issues/7) in the meantime, and provide feedback.\n\n### Usage with other frameworks\n\nstorybook-django’s implementation is largely framework-agnostic, and should work equally as well with Storybook’s HTML and Web Components support.\n\nYou will need to directly import the imperative APIs:\n\n```js\nimport {\n  renderPattern,\n  simulateLoading,\n  insertHTMLWithScripts,\n} from 'storybook-django';\n```\n\n- `renderPattern` calls the django-pattern-library API rendering endpoint.\n- `simulateLoading` includes `insertHTMLWithScripts`, and fires a `DOMContentLoaded` event.\n- `insertHTMLWithScripts` is like `.innerHTML`, but additionally executing any `\u003cscript\u003e` tags.\n\n### TypeScript usage\n\nThere is nothing particular to change to make storybook-django work with TypeScript. Just make sure to configure TypeScript to understand `.md` and `.html` files if you use those features – here is a sample `stories.d.ts` file:\n\n```ts\ndeclare module '*.md';\ndeclare module '*.html';\n```\n\n### Tag overrides\n\n[Tag overrides](https://torchbox.github.io/django-pattern-library/guides/overriding-template-tags/) are a feature of django-pattern-library. They’re very simple to use with storybook-django too. Here is an example:\n\n```js\nimport React from 'react';\nimport { Pattern, generateDocs } from 'storybook-django/src/react';\n\nimport template from './page_status_tag_new.html';\n\nexport default {};\n\nconst PublicTemplate = (args) =\u003e (\n  \u003cPattern\n    filename={__filename}\n    tags={{\n      test_page_is_public: {\n        'page as is_public': {\n          raw: false,\n        },\n      },\n    }}\n    context={{ page: args }}\n  /\u003e\n);\n\nexport const Public = PublicTemplate.bind({});\nPublic.args = {\n  live: true,\n  url: '#',\n};\n```\n\nThis is the same API as that of django-pattern-library, but as JS objects rather than YAML.\n\n### Advanced usage\n\n`storybook-django` is still very experimental. Head over to [Discussions](https://github.com/torchbox/storybook-django/discussions) to share information about more advanced usage.\n\n#### Storyshots support\n\n`storybook-django` is compatible with Storyshots, with a few constraints due to rendering happening with Django via an API:\n\n1. We need a running Django server while the Storyshots test suite is running.\n2. Components render asynchronously, so we need to make sure to test the final rendering _from Django_, rather than an intermediary state.\n3. We need to use Jest’s `jsdom` environment, and include a polyfill for `window.fetch` such as `whatwg-fetch`.\n\nGetting a Django server up and running is as simple as starting it in the background ahead of running the test suite. Here is a [GitHub Actions example](https://github.com/torchbox/storybook-django/blob/main/.github/workflows/ci.yml#L48-L70):\n\n```yaml\n- run: source .venv/bin/activate \u0026\u0026 python manage.py runserver 0:8001 \u0026\n- run: npm run test\n```\n\nTo check whether Django patterns have finished rendering, we use a `data-state=\"loaded\"` attribute set by storybook-django when it first inserts the HTML into the DOM. Here is an [example of automated accessibility tests with Axe](https://github.com/torchbox/storybook-django/blob/main/demo/static_src/tests/storyshots-axe.test.js), with `@testing-library/react`:\n\n```js\nconst { container, queryAllByTestId } = render(story.render());\n\nconst patterns = queryAllByTestId('storybook-django');\n\nif (patterns.length \u003e 0) {\n  await waitFor(\n    () =\u003e expect(patterns.map((p) =\u003e p.dataset.state)).toContain('loaded'),\n    { timeout: 10000 },\n  );\n}\n```\n\n#### Storyshots: snapshots\n\nAfter checking the patterns are loaded, it’s as simple as `expect(container).toMatchSnapshot();`. See the [full snapshot example](https://github.com/torchbox/storybook-django/blob/main/demo/static_src/tests/storyshots-snapshot.test.js).\n\n#### Storyshots: accessibility\n\nWith `jest-axe`, after checking the patterns are loaded,\n\n```js\nconst results = await axe(container, {\n  // See https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md for a list of rules.\n  // Try to only disable rules if strictly needed, alternatively also consider excluding stories from those tests\n  // with the `storyshots` parameter: https://github.com/storybookjs/storybook/tree/master/addons/storyshots/storyshots-core#disable.\n  rules: {\n    // Disabled because stories are expected to be rendered outside of landmarks for testing.\n    region: { enabled: false },\n  },\n});\n\nexpect(results).toHaveNoViolations();\n```\n\nSee the [full jest-axe example](https://github.com/torchbox/storybook-django/blob/main/demo/static_src/tests/storyshots-axe.test.js).\n\n#### Storyshots: image snapshots\n\nThis is possible as well, with Storybook’s `@storybook/addon-storyshots-puppeteer`. View the [full image snapshots example](https://github.com/torchbox/storybook-django/blob/main/demo/static_src/tests/storyshots-image-snapshot.test.js).\n\n#### YAML for mock context and tags\n\nA few of the stories in our demo project use YAML to store a pattern’s mock context and tags. This is largely a demonstration of compatibility with how [django-pattern-library](https://github.com/torchbox/django-pattern-library) works, and for most users defining context and tags with Storybook APIs is more suitable. There are a few cases where the YAML setup can help:\n\n- There is currently no way to override context in _other templates_ via API calls. YAML files make this possible.\n- Similarly there is no way to override tags in other templates – again made possible with YAML files.\n\n### Hosting\n\nSince storybook-django relies on a Django backend, in this context the Storybook export can’t be hosted as a fully static site. We instead need to:\n\n1. Build a static export with `build-storybook`\n2. Configure a Django server to serve the static export\n3. Host the Django server\n\nThis repository’s `demo` site has an example of how to do this, serving the static files with Django’s `django.views.static.serve`.\n\n## Common questions\n\n### How does this compare with django-pattern-library?\n\n[django-pattern-library](https://github.com/torchbox/django-pattern-library) makes it possible to work with Django templates as UI components. It comes with its own rudimentary pattern library UI. storybook-django uses [Storybook](https://storybook.js.org/)’s UI instead, and Storybook’s APIs to work on components, write tests, and documentation.\n\n### Features comparison table\n\n| Feature                                 | django-pattern-library                                                                                                                                                    | storybook-django                                                                                                                                                        |\n| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| UI framework support                    | Vanilla Django templates only                                                                                                                                             | Vanilla templates and all frameworks Storybook supports                                                                                                                 |\n| Dependencies                            | 1 PyPI package                                                                                                                                                            | 1 PyPI package, 1 npm package, all Storybook dependencies                                                                                                               |\n| Hosting                                 | Django server or [static site export](https://torchbox.github.io/django-pattern-library/guides/static-site-export/)                                                       | Django server only                                                                                                                                                      |\n| Components documentation                | Separate Markdown file                                                                                                                                                    | Storybook [Docs addon](https://storybook.js.org/addons/@storybook/addon-docs) with separate Markdown file, or Django templates comments extraction, or write in stories |\n| Browser support                         | No restrictions                                                                                                                                                           | Modern browsers only                                                                                                                                                    |\n| Live reload                             | No (bring your own)                                                                                                                                                       | Yes, if configured                                                                                                                                                      |\n| View components at multiple breakpoints | Yes, with [predefined breakpoints only](https://github.com/torchbox/django-pattern-library/issues/101)                                                                    | Yes, with [viewport addon](https://storybook.js.org/docs/react/essentials/viewport)                                                                                     |\n| Tweak template data in UI               | No                                                                                                                                                                        | Yes, Storybook [controls](https://storybook.js.org/docs/react/essentials/controls)                                                                                      |\n| Component variations                    | [No](https://torchbox.github.io/django-pattern-library/reference/known-issues/#no-support-for-pattern-variations)                                                         | Yes                                                                                                                                                                     |\n| Component status                        | [No](https://github.com/torchbox/django-pattern-library/issues/91)                                                                                                        | Yes, with Docs addon                                                                                                                                                    |\n| Components homepage                     | [No](https://github.com/torchbox/django-pattern-library/issues/94) (build your own)                                                                                       | No (build your own)                                                                                                                                                     |\n| Pattern library theming                 | [No](https://github.com/torchbox/django-pattern-library/issues/107)                                                                                                       | Yes                                                                                                                                                                     |\n| Customizing a component’s surroundings  | No, [create a new template for this](https://torchbox.github.io/django-pattern-library/guides/customizing-template-rendering/#customizing-a-single-patterns-surroundings) | Yes                                                                                                                                                                     |\n| Automated snapshot tests                | [Basic support](https://torchbox.github.io/django-pattern-library/guides/automated-tests/#with-render_patterns)                                                           | Yes, with [Storyshots](https://storybook.js.org/addons/@storybook/addon-storyshots)                                                                                     |\n| Automated accessibility tests           | [Basic support](https://torchbox.github.io/django-pattern-library/guides/automated-tests/#accessibility-testing)                                                          | Yes, with [Storyshots](https://storybook.js.org/addons/@storybook/addon-storyshots) or [a11y addon](https://www.npmjs.com/package/@storybook/addon-a11y)                |\n| Automated visual regression tests       | [Basic support](https://torchbox.github.io/django-pattern-library/guides/automated-tests/#visual-regression-testing)                                                      | Yes, with [Storyshots](https://storybook.js.org/addons/@storybook/addon-storyshots) or any other Storybook integration                                                  |\n\n### How does this compare with Storybook’s official server support?\n\nCompared to this project, [`@storybook/server`](https://www.npmjs.com/package/@storybook/server) only supports simple use cases.\n\n### What is the future of storybook-django?\n\nSee [torchbox/django-pattern-library#103 – Storybook prototype of the pattern library](https://github.com/torchbox/django-pattern-library/issues/103) for more context on this project, and to keep up with changes to it in relation with django-pattern-library.\n\n### Should I use storybook-django, or stick with django-pattern-library only?\n\nAre Storybook’s capabilities appealing to you? Consider using storybook-django. If not, stick with django-pattern-library if you’re ok with its [known limitations](https://torchbox.github.io/django-pattern-library/reference/known-issues/). It’s simpler to start with django-pattern-library and add Storybook later, than the other way around.\n\n## Contributing\n\nSee anything you like in here? Anything missing? We welcome all support, whether on bug reports, feature requests, code, design, reviews, tests, documentation, and more. Please have a look at our [contribution guidelines](docs/CONTRIBUTING.md).\n\nIf you just want to set up the project on your own computer, the contribution guidelines also contain all of the setup commands.\n\n## Credits\n\nView the full list of [contributors](https://github.com/torchbox/storybook-django/graphs/contributors). [MIT](LICENSE) licensed.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftorchbox%2Fstorybook-django","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftorchbox%2Fstorybook-django","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftorchbox%2Fstorybook-django/lists"}