I have a working implementation of autocomplete_light in my django project, pulling values from cities_light in a dropdown, which correctly saves the foreign key to the field in the db on form submit. When I revisit the form, I would like for the autocomplete text field to default to the value that is saved, ideally with the value in plain text and with an "X" button (like that is already built in). Currently, I see placeholder text and a blank text field. Other saved values in the form (omitted here) are being defaulted correctly when I revisit the form. What do I need to add here to trigger the widget to present the saved value? Here is my code:
forms.py
class UserProfileForm(autocomplete_light.GenericModelForm):
location = autocomplete_light.GenericModelChoiceField(
widget=autocomplete_light.ChoiceWidget(
autocomplete='AutocompleteItems',
autocomplete_js_attributes={'placeholder':'City, State, Country',
'minimum_characters': 3})
)
class Meta:
model = UserProfile
fields = ['location']
models.py
class UserProfile(models.Model):
user = models.ForeignKey(
User,
unique=True
)
location = models.ForeignKey(
City,
blank=True,
null=True
)
autocomplete_light_registry.py
class AutocompleteItems(autocomplete_light.AutocompleteGenericBase):
choices = (
City.objects.all(),
)
search_fields = (
('search_names',),
)
autocomplete_light.register(AutocompleteItems)
I know this post is more than 1 year old but the answer might help someone. I managed to populate the autocomplete-light widget by adding the extra_context parameter to ChoiceWidget in the form init.
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.initial.get('city', None):
cityPK = self.initial['city']
city = cities_light.models.City.objects.get(pk=cityPK)
self.fields['city_name'].widget=autocomplete_light.ChoiceWidget('CityAutocomplete', extra_context={'values':[cityPK], 'choices':[city]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With