6

我在我的 django 项目中有一个 autocomplete_light 的工作实现,在下拉列表中从 city_light 中提取值,这会在表单提交时正确地将外键保存到数据库中的字段。当我重新访问表单时,我希望自动完成文本字段默认为保存的值,最好是纯文本中的值和“X”按钮(就像已经内置的那样)。目前,我看到占位符文本和空白文本字段。当我重新访问表单时,表单中的其他保存值(此处省略)被正确默认。我需要在此处添加什么来触发小部件以显示保存的值?这是我的代码:

表格.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']

模型.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)
4

1 回答 1

4

我知道这篇文章已有 1 年多的历史,但答案可能对某人有所帮助。我设法通过在表单初始化中将 extra_context 参数添加到 ChoiceWidget 来填充 autocomplete-light 小部件。

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]})
于 2015-01-16T14:58:51.267 回答