Package: django-dynamic-admin-forms
Add simple interactions to the otherwise static django admin.PyPIGitHubFull documentationCreator & Maintainer:Ambient Digitaldjango-dynamic-admin-formsAdd simple interactions to the otherwise static django admin.InstallationInstall the package via pip:pip install django-dynamic-admin-formsor via pipenv:pipenv install django-dynamic-admin-formsAdd the module toINSTALLED_APPS:INSTALLED_APPS=(...,'django_dynamic_admin_forms','django.contrib.admin'...)Ensure that thedynamic_admin_formscomes before the
defaultdjango.contrib.adminin the list of installed apps,
because otherwise the templates, which are overwritten bydynamic_admin_formswon't be found.Ensure that thedynamic_admin_formstemplates are found via usingAPP_DIRSsetting:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','APP_DIRS':True,...},]Runpython manage.py collectstaticto include this apps Javascript code in yoursettings.STATIC_ROOTdirectoryUsageAdd thedjango_dynamic_admin_forms.DynamicModelAdminMixinto your admin classesAdd thedjango_dynamic_admin_forms.urlsto your urlsfromdjango.contribimportadminfromdjango.urlsimportpath,includeurlpatterns=[path("admin/",admin.site.urls),path("dynamic-admin-form/",include("django_dynamic_admin_forms.urls")),]In addition to the standardfieldsdeclaration, specify a list ofdynamic_fieldsFor each dynamic field, add a methodget_dynamic_{field_name}_fieldto the adminInput:data: Dict[str, Any]- the cleaned form dataOutput:queryset: Optional[Queryset]- The values to select fromvalue: Any- The value, the field should have (must be compatible to the field type)hidden: Bool- True, if field should be hiddenA rather non-sensical example:fromdjango.contribimportadminfrom.modelsimportMyModelfromdjango_dynamic_admin_forms.adminimportDynamicModelAdminMixin@admin.register(MyModel)classMyModelAdmin(DynamicModelAdminMixin,admin.ModelAdmin):fields=("name","city")dynamic_fields=("city",)defget_dynamic_city_field(self,data):# automatically choose first city that matches first letter of namename=data.get("name")ifnotname:queryset=City.objects.all()value=data.get("city")else:queryset=City.objects.filter(name__startswith=name[0])value=queryset.first()hidden=notqueryset.exists()returnqueryset,value,hiddenHow it worksWhenever a dynamic form changes, an event handler makes a request to a special endpoint, which returns new HTML to swap
into  the existing form. This new HTML is directly generated bydjango.contrib.admin, so we only have to set the
outerHTML of the correct HTML elements to update the form.Limitationsdoes not work in conjunction with inlinesdoes not validate that the selected value is really part of the original querysetif anybody can modify your DOM, they could potentially inject invalid valuesyou have to writeModel.clean()methods to guard against thatonly tested with Django 3.2DevelopmentFor local development, create a virtual environment
in thetestprojfolder:$cdtestapp
$python3-mvenv.venv
$source.venv/bin/activate
$cd..
$pipinstall-e.Now the package should be available in your virtual environment
and any changes should be directly visible. Run the project as a Django server and navigate to the admin page.Alternatively, copy the directorydynamic_admin_formsinto any normal django project, so that the python interpreter
finds the local version instead of the installed (old) version.Running E2E testsTo run end-to-end tests locally:$cdtestapp
$pythonmanage.pyrunserver0.0.0.0:8000&# start server$pythonmanage.pyloaddatafixtures/fixtures-dev.json
$cd../e2e
$yarninstall# or npm install (only needed first time)$yarncypress# or npm run cypressInstallationInstall the package via pip:pip install django-dynamic-admin-formsor via pipenv:pipenv install django-dynamic-admin-formsAdd the module toINSTALLED_APPS:INSTALLED_APPS=(...,'django_dynamic_admin_forms','django.contrib.admin'...)Ensure that thedynamic_admin_formscomes before the
defaultdjango.contrib.adminin the list of installed apps,
because otherwise the templates, which are overwritten bydynamic_admin_formswon't be found.Ensure that thedynamic_admin_formstemplates are found via usingAPP_DIRSsetting:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','APP_DIRS':True,...},]Runpython manage.py collectstaticto include this apps Javascript code in yoursettings.STATIC_ROOTdirectoryContributeSetup package for developmentCreate a Python virtualenv and activate itInstall "pip-tools" withpip install -U pip-toolsCompile the requirements withpip-compile --extra dev, -o requirements.txt pyproject.toml --resolver=backtrackingSync the dependencies with your virtualenv withpip-syncAdd functionalityCreate a new branch for your featureChange the dependency in your requirements.txt to a local (editable) one that points to your local file system:-e /Users/workspace/django-dynamic-admin-formsor via pippip install -e /Users/workspace/django-dynamic-admin-formsEnsure the code passes the testsCreate a pull requestRun testsRun testspytest --ds settings testsCheck coveragecoverage run -m pytest --ds settings tests
coverage report -mGit hooks (via pre-commit)We use pre-push hooks to ensure that only linted code reaches our remote repository and pipelines aren't triggered in
vain.To enable the configured pre-push hooks, you need toinstallpre-commit and run once:pre-commit install -t pre-push -t pre-commit --install-hooksThis will permanently install the git hooks for both, frontend and backend, in your local.git/hooksfolder.
The hooks are configured in the.pre-commit-config.yaml.You can check whether hooks work as intended using theruncommand:pre-commit run [hook-id] [options]Example: run single hookpre-commit run ruff --all-files --hook-stage pushExample: run all hooks of pre-push stagepre-commit run --all-files --hook-stage pushUpdate documentationTo build the documentation run:sphinx-build docs/ docs/_build/html/.Opendocs/_build/html/index.htmlto see the documentation.Translation filesIf you have added custom text, make sure to wrap it in_()where_is
gettext_lazy (from django.utils.translation import gettext_lazy as _).How to create translation file:Navigate todjango-dynamic-admin-formspython manage.py makemessages -l deHave a look at the new/changed files withindjango_dynamic_admin_forms/localeHow to compile translation files:Navigate todjango-dynamic-admin-formspython manage.py compilemessagesHave a look at the new/changed files withindjango_dynamic_admin_forms/localePublish to ReadTheDocs.ioFetch the latest changes in GitHub mirror and push themTrigger new build at ReadTheDocs.io (follow instructions in admin panel at RTD) if the GitHub webhook is not yet set
up.Publish to PyPiUpdate documentation about new/changed functionalityUpdate theChangelogIncrement version in main__init__.pyCreate pull request / merge to masterThis project uses the flit package to publish to PyPI. Thus publishing should be as easy as running:flit publishTo publish to TestPyPI use the following ensure that you have set up your .pypirc as
shownhereand use the following command:flit publish --repository testpypiMaintenancePlease note that this package supports theambient-package-update.
So you don't have to worry about the maintenance of this package. All important configuration and setup files are
being rendered by this updater. It works similar to well-known updaters likepyupgradeordjango-upgrade.To run an update, refer to thedocumentation pageof the "ambient-package-update".