2

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.

Hofmann
  • 118
  • 1
  • 8
  • Hi Hofmann, I am working on the same issue and was not able to fix it. Can you please give me a example of your HTML template? Is your addanother widget still part of the forms.py? – Napsterlicious Nov 23 '21 at 11:12

0 Answers0