I'm trying to implement django-autocomplete-light and django-addanother for the same field in a ModelForm
.
I've tried the following:
import floppyforms.__future__ as forms
from .models import Worker
from dal import autocomplete
from organizations.models import Hub
from django.urls import reverse_lazy
from django_addanother.widgets import AddAnotherWidgetWrapper
from django.forms import MultiWidget
class WorkerCreateForm(forms.ModelForm):
class Meta:
model = Worker
fields = ['display_name', 'hub', 'capacity', 'vehicle', ]
widgets = {
'hub': autocomplete.ModelSelect2(url='hubs-autocomplete', attrs{'data-html': True}),
'hub': AddAnotherWidgetWrapper(
forms.Select,
reverse_lazy('create_hub'))
}
This will only render the AddAnotherWidgetWrapper
obviously.
I've tried to use MultiWidget in multiple ways and every time I got a different error (I will not post all my trials and errors since most of them don't make a lot of sense, but if you think I should share them I would be happy to do so). I'm finding it hard to understand how to use MultiWidget
since there are no clear examples, and I'm not sure if it's the right solution for my use case.
In django-autocomplete-light's documentation, they recommend using django-addanother
for adding a model with multiple fields, but there's no explanation on how to implement it.
I'm guessing that it might not be easy to fill the newly created model by django-addanother
in the Select2
dropdown, but if I can just have the ability to create a new model and then let the user choose it manually in the select field, it will be enough for me.
I'd like to know if there's an easy way to use both packages together or if I should write my own custom code to make both packages work together nicely.
Any help would be greatly appreciated.
EDIT: I ended up placing the django-addanother
JavaScript scripts manually in the HTML template and it worked. However, I'm not sure if it is the best implementation and if it will cause any security issues.