Popups in django forms?

98 views
Skip to first unread message

zvo...@seznam.cz

unread,
Feb 26, 2021, 4:14:54 AM2/26/21
to Django users
I want start a new project with good support for popups (select+options) in forms.

My requirements are (and I think for real life project they are neccessary):
1. ajax retrieved options based on users selection (outside of admin and inside admin),
2. dynamic filtering of (especially related) options (again outside/inside admin, include admin inlines); example: country & city: only cities from selected country should be accessible.

I have implemented this
include (2) functionality in inlines and it works.

However it requires to much individual work in each case and doesn't combine with ajax.

Is there a better way how to achieve (1)+(2) everywhere in application?
Are there some packages? What about django-autocomplete-light?

Best regards,
Mirek

zvo...@seznam.cz

unread,
Mar 3, 2021, 7:41:43 AM3/3/21
to Django users
No response for this topic for some time, so I will try partially answer myself.

Admin Django starting from version 2.0 has autocomplete_fields.
These are relalational fields (ForeignKey, ManyToManyField), targeted into other ModelAdmin, which find content for their widget via ajax at the url autocomplete/.
It works together with the .search_fields attribute of the targeted ModelAdmin.
.search_fields says, in which fields should be searched the string, which user will enter into the popup widget.
.search_fields can be replaced using .get_search_results().

Django implementation is weak. Problem is that the implementation doesn't think at all about the situation when 2 different ForeignKey-s target into same model.
Example: If you have in model 2 fields "Owner" and "Responsible", both targeted into User model, Django cannot in .get_search_results() find, which of them you just enter and how the accesible options should be filtered.
It is possible to make a trick with modyfiing of the Referer adress (request.headers['Referer']). We could add something like ?key=..., so .get_search_results() has then information, which one ForeignKey asks for results.
I made some experiments with this earlier and in github.com/pyutil/django-admin-autocomplete-all it is implemented (and a little commented with an usage example) in `autocomplete_all/js/autocomplete_params.js`.
Just inspiration, because I don't think that this package is perfect and its documentation well.

Django 2+ autocomplete_fields however cannot be used outside of Admin.
So we have 2 ways how to go:
1) Use django-autocomplete-light everywhere and ignore the possibility of Dj2 autocomplete_fields,
or 2) inside the Admin to prefer the native possibility: autocomplete_fields.

Dne pátek 26. února 2021 v 10:14:54 UTC+1 uživatel zvo...@seznam.cz napsal:
Reply all
Reply to author
Forward
0 new messages