{"id":13780721,"url":"https://github.com/PHACDataHub/django-htmx-autocomplete","last_synced_at":"2025-05-11T14:33:47.167Z","repository":{"id":64512959,"uuid":"567455646","full_name":"PHACDataHub/django-htmx-autocomplete","owner":"PHACDataHub","description":"A Django autocomplete component powered by htmx","archived":false,"fork":false,"pushed_at":"2024-10-17T13:31:41.000Z","size":161,"stargazers_count":50,"open_issues_count":9,"forks_count":4,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-10-19T19:07:07.289Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","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/PHACDataHub.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"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":"2022-11-17T20:39:25.000Z","updated_at":"2024-10-15T01:16:29.000Z","dependencies_parsed_at":"2024-08-03T18:12:14.933Z","dependency_job_id":"591c01e1-13f0-46b8-b513-66d8019ff0a9","html_url":"https://github.com/PHACDataHub/django-htmx-autocomplete","commit_stats":{"total_commits":40,"total_committers":5,"mean_commits":8.0,"dds":0.475,"last_synced_commit":"15fb124eca99e8e97313ed61737beab7fe9c9389"},"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PHACDataHub%2Fdjango-htmx-autocomplete","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PHACDataHub%2Fdjango-htmx-autocomplete/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PHACDataHub%2Fdjango-htmx-autocomplete/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PHACDataHub%2Fdjango-htmx-autocomplete/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PHACDataHub","download_url":"https://codeload.github.com/PHACDataHub/django-htmx-autocomplete/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225064365,"owners_count":17415238,"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":[],"created_at":"2024-08-03T18:01:19.067Z","updated_at":"2025-05-11T14:33:47.138Z","avatar_url":"https://github.com/PHACDataHub.png","language":"Python","funding_links":[],"categories":["Third Party Packages 📦 \u003ca name = \"tools\"\u003e\u003c/a\u003e"],"sub_categories":["Components"],"readme":"# django-htmx-autocomplete\n\nThis Django app provides an autocomplete widiget component powered by\n[htmx](https://htmx.org/) featuring multiselect, search and is completely extensible.\n\n## Quick start\n\n1. Install the `django-htmx-autocomplete` package\n\n   ```shell\n   pip install django-htmx-autocomplete\n   ```\n\n2. Add \"autocomplete\" to your `INSTALLED_APPS` setting like this:\n\n   ```python\n   # settings.py\n   INSTALLED_APPS = [\n       ...\n       'django.contrib.staticfiles',  # also required\n       'autocomplete',\n   ]\n   ```\n\n3. Include the autocomplete urls like this:\n\n   ```python\n   # urls.py\n   ...\n    from autocomplete import urls as autocomplete_urls\n\n   urlpatterns = [\n       # ...\n        path(\"ac/\", autocomplete_urls),\n   ]\n   ```\n\n\n4. Create an `@register`d autocomplete class that extends `autocomplete.ModelAutocomplete`,\n\nRegistration allows views to reach your class. If you have abstract autocomplete classes, don't register those.\n\n   ```python\n   from django forms\n   from django.db import models\n   import autocomplete\n\n\n   class Person(models.Model):\n       name = models.CharField(max_length=60)\n\n   class Team(models.Model):\n        team_lead = models.ForeignKey(\n            Person, null=True, on_delete=models.SET_NULL, related_name=\"lead_teams\"\n        )\n\n       members = models.ManyToManyField(Person)\n\n   @autocomplete.register\n   class PersonAutocomplete(autocomplete.ModelAutocomplete):\n       model = Person\n       search_attrs = [ 'name' ]\n\n\n   class MultipleFormModel(forms.ModelForm):\n   \"\"\"Multiple select example form using a model\"\"\"\n       class Meta:\n           \"\"\"Meta class that configures the form\"\"\"\n           model = Team\n           fields = ['team_lead', 'members']\n           widgets = {\n                'team_lead': autocomplete.AutocompleteWidget(\n                    ac_class=PersonAutocomplete,\n                ),\n               'members': autocomplete.AutocompleteWidget(\n                    ac_class=PersonAutocomplete,\n                    options={\"multiselect\": True},\n               )\n           }\n   ```\n\n5. Make sure your templates include HTMX.\n\n   \u003e **Note**\n   \u003e Bootstrap is included in this example styling, however it is not required.\n\n   ```django\n   {% load autocomplete %}\n   {% load static %}\n   \u003c!doctype html\u003e\n   \u003chtml lang=\"en\"\u003e\n     \u003chead\u003e\n       \u003c!-- Bootstrap --\u003e\n       \u003clink href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\"\n   integrity=\"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi\" crossorigin=\"anonymous\"\u003e\n     \u003c/head\u003e\n     \u003cbody\u003e\n       \u003ch1\u003eExample base html template\u003c/h1\u003e\n       \u003c!-- Bootstrap --\u003e\n       \u003cscript src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3\" crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n       \u003c!-- htmx --\u003e\n       \u003cscript src=\"https://unpkg.com/htmx.org@1.8.3\" integrity=\"sha384-e2no7T1BxIs3ngCTptBu4TjvRWF4bBjFW0pt7TpxOEkRJuvrjRt29znnYuoLTz9S\" crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n       \u003c!-- htmx csrf --\u003e\n       \u003cscript\u003e\n         document.body.addEventListener('htmx:configRequest', (event) =\u003e {\n           event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';\n         });\n       \u003c/script\u003e\n     \u003c/body\u003e\n   \u003c/html\u003e\n   ```\n\n## Using the widget\n\n- The widget will receive its name, required-ness and disabled-ness from the form field, these work out of the box, including for formsets and prefixed forms.\n- Options that can be tweaked on the fly via widget `options` are,\n  - multiselect\n    - If you want to use the widget in on a multiple-choice field (e.g. a many-to-many field), you can pass an options dict with `multiselect=True` in it\n  - placeholder\n    - default: \"\"\n  - component_prefix\n    - this is for a niche use-case where you want multiple inputs with the same `name` attribute. In that case and you don't set unique prefixes, the autocomplete widget may not work correctly due to duplicate HTML IDs.\n\nOther options are set less dynamically, by customizing the the autocomplete class...\n\n## Autocomplete class customization\n\n### `minimum_search_length`\n\ndefault: 3\n\nexample:\n\n```python\nclass MyAC(Autocomplete):\n    minimum_search_length = 2\n```\n\n### `max_results`\n\nThis library does not yet support pagination, but it will efficiently limit results and tell the user there how many results are missing.\n\n```python\nclass MyAC(Autocomplete):\n    max_results = 10\n\n```\n\n### `component_prefix`\n\n- In addition to widget options, you can also set the `component_prefix` option on the class itself. Widget options will take precedence over the class.\n- default: \"\"\n\n### `placeholder`\n\n- In addition to widget options, you can also set the `placeholder` option on the class itself. Widget options will take precedence over the class.\n- default: \"\"\n\n### Translation strings\n\nYou can customize the translation strings used in the autocomplete widget by overriding class variables on your autocomplete class,\n\n- `no_result_text`\n  - default: \"No results found.\"\n- `narrow_search_text`\n  - default: \"Showing %(page_size)s of %(total)s items. Narrow your search for more results.\"\n- `type_at_least_n_characters`\n  - default: \"Type at least %(n)s characters\"\n\nnote that the `%(n)s` and `%(page_size)s` and `%(total)s` are placeholders that will be replaced with the actual values at runtime. If you write your own strings, make sure to use the `%(n)s` rather than `%(n)d`. Variables are converted to strings so the integer formatter will not work.\n\nexample:\n\n```python\nclass MyAC(Autocomplete):\n    no_result_text = \"No results found\"\n    narrow_search_text = \"Please narrow your search\"\n    type_at_least_n_characters = \"Type at least %(n)s characters\"\n```\n\n### Authentication-aware behaviour\n\nAutocomplete adds 2 new views that any user, including non-authenticated users, can access. Autocomplete classes have a `auth_check` method you can override to add authentication checks. For example, if you want to restrict access to a certain autocomplete to only authenticated users, you can do the following,\n\n```python\nfrom autocomplete import Autocomplete, register\n\n@register\nclass MyAC(Autocomplete):\n    # ...\n\n    @staticmethod\n    def auth_check(request):\n        if not request.user.is_authenticated:\n            raise PermissionDenied(\"Must be logged in\")\n\n```\n\nThis is a common enough use case that we've added a setting shortcut. Add `AUTOCOMPLETE_BLOCK_UNAUTHENTICATED=False` in your settings and all autocomplete views will require authentication by default.\n\n## Non model approach\n\nThe model autocomplete is a subclass of the more generic `autocomplete.Autocomplete` class. You can use this class to create an autocomplete that does not rely on a model. There are two important methods to provide,\n\n1. `search_items(cls, search, context)`\n   - Must return an iterable of `{ key: string, label: string }` dictionaries. This iterable must allow slicing and len() to be called on it.\n2. `get_items_from_keys(cls, keys, context)`\n   - Must return a list of `{ key: string, label: string }` dictionaries. This list must be the same length as the input keys list.\n   - This is used to render existing items in the autocomplete widget.\n\nThe context argument is a simple namespace type:\n\n```python\n@dataclass\nclass ContextArg:\n    request: HttpRequest\n    client_kwargs: django.http.QueryDict\n    # this is a redundant reference to request.GET\n```\n\nWe may add additional attributes on this object in the future.\n\nIf you're still using models but want different logic than the model-autocomplete, consider cracking open the `ModelAutocomplete` class and seeing how it works. It's probably easier to override its particular methods than to start from scratch and implement an efficient iterable that wraps querysets.\n\n## Tip: Custom Autocomplete base class\n\nIf you have several autocompletes in your project, we recommend creating a base autocomplete class that extends `autocomplete.Autocomplete` and using that as your project-wide base class. Here you can customize translation strings, authentication-aware behaviour, min-search-length, max-results-count, etc. This way, you're also insulated from changes in our defaults.\n\n# Contributing\n\nTo set up the development environment, follow these steps:\n\n```bash\n# from root of project,\npip install -r requirements.txt\n\n# running tests,\npython manage.py test tests/\n\n# running app locally\npython manage.py migrate\npython manage.py runscript sample_app.dev_script\npython manage.py runserver\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPHACDataHub%2Fdjango-htmx-autocomplete","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FPHACDataHub%2Fdjango-htmx-autocomplete","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPHACDataHub%2Fdjango-htmx-autocomplete/lists"}