OmenApps / django-tomselect

Autocomplete widgets and views using TomSelect
MIT License
18 stars 1 forks source link

When loading a form with `instance` set to an object, existing data isn't displayed #4

Open vtbassmatt opened 1 year ago

vtbassmatt commented 1 year ago

When I try to edit an existing model instance, the Tom-Select widget isn't prepopulated with the current data the way the default Django Select widget does.

Default Django Select widget:

default Django Select widget showing prepopulated data

Swapping out for this Tom-Select widget:

Tom-Select widget with no prepopulated data

(I don't show it here in the issue, but clicking the dropdown does correctly load all the City objects.)

Repro files ```python # app/models.py from django.db import models class City(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Place(models.Model): name = models.CharField(max_length=200) city = models.ForeignKey(City, on_delete=models.PROTECT) def __str__(self): return self.name ``` ```python # app/forms.py from app.models import Place, City from django import forms from django_tomselect.widgets import TomSelectWidget class PlaceForm(forms.ModelForm): class Meta: model = Place fields = ('name', 'city') widgets = {'city': TomSelectWidget(City, 'city-auto'),} ``` ```python # app/views.py from django.shortcuts import render from .forms import PlaceForm from .models import Place def index(request): instance = Place.objects.get(pk=1) form = PlaceForm(instance=instance) return render(request, 'index.html', {'form': form}) ``` ```python # project/urls.py from django.contrib import admin from django.urls import path from django_tomselect.views import AutocompleteView from app import views urlpatterns = [ path('admin/', admin.site.urls), path('tom/', AutocompleteView.as_view(), name='city-auto'), path('', views.index), ] ``` ```html Django Tom Select Demo {{ form.media }}
{% csrf_token %} {{ form.as_div }}
``` ```python # interactive session to populate data from app.models import Place, City raleigh = City(name='Raleigh') raleigh.save() Place(name='Trophy', city=raleigh).save() ```
vtbassmatt commented 1 year ago

Ah, after some more poking, it's because of https://github.com/jacklinke/django-tomselect/blob/c777a84cc31c5ec3af4909a5cec758fa26d521c9/src/django_tomselect/widgets.py#L78-L79 (optgroups always returns []). I understand why that line wants to not read the entire queryset, but I'll see if I can patch it to return the currently-selected data.

vtbassmatt commented 1 year ago

django-autcomplete-light (another MIT-licensed improvement on standard Select widgets) has this implementation: https://github.com/yourlabs/django-autocomplete-light/blob/2e51796eefe37a8efa6b66420e3e355cb73edc91/src/dal/widgets.py#L129-L145

It seems to work here as well. I'll put up a PR.