django-autocomplete-light default load a previously saved value?
Asked Answered
M

1

6

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)
Morula answered 4/1, 2014 at 21:24 Comment(1)
That would not work very well and that's why django-autocomplete-light doesn't provide such a feature. There are cases when you just can't maintain sync between the text field and the actual value in a hidden pk. I can't take time to explain everything right now but you can figure it out by trying to plan how your implementation would work on paper. As the author of django-autocomplete-light and I have no idea why you have been downvoted so I'm going to upvote to compensate. However, you should try django-autocomplete-light v2 which is designed more like what you're saying.Klaus
T
4

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]})
Tertias answered 16/1, 2015 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.