我在 Wagtail 项目中的 CustomUser 模型中添加了两个附加字段。这两个字段是多对多 (m2m) 字段,在表单中,我希望将这些字段表示为自动完成功能。我怎样才能实现这个目标?
模型.py
class User(AbstractUser):
journal = models.ManyToManyField("journal.Journal", verbose_name=_("Journal"), blank=True)
collection = models.ManyToManyField("collection.Collection", verbose_name=_("Collection"), blank=True)
表格.py
class CustomUserEditForm(UserEditForm):
journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal"))
collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection"))
class CustomUserCreationForm(UserCreationForm):
journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal"))
collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection"))
我们使用https://django-autocomplete-light.readthedocs.io/en/master/
from dal import autocomplete
FieldPanel(
'sponsors',
heading='Event Sponsors',
widget=autocomplete.ModelSelect2Multiple(
url='master_calendar_public:event_sponsor_autocomplete',
attrs={'data-placeholder': 'Search for Event Sponsors...', 'data-language': 'en'},
)
如您所见,您将需要一个执行自动完成 AJAX 部分的视图。
class EventSponsorAutocompleteView(autocomplete.Select2QuerySetView):
# No pagination is necessary for these objects. There just aren't enough to matter, and a paginated <select> is a
# pretty poor user experience.
paginate_by = None
def get_queryset(self):
queryset = EventSponsor2.objects.all()
# If the user has typed anything into the autocomplete widget, filter the queryset down to Sponsors that match.
if self.q:
queryset = queryset.filter(name__icontains=self.q)
return queryset