jquery - django-autocomplete-light 默认加载以前保存的值?

标签 jquery python django forms django-autocomplete-light

我在我的 django 项目中有一个 autocomplete_light 的工作实现,从下拉列表中的 cities_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)

最佳答案

我知道这篇文章已有 1 年多的历史,但答案可能会对某些人有所帮助。我设法通过将 extra_context 参数添加到表单 init 中的 ChoiceWidget 来填充自动完成灯小部件。

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]})

关于jquery - django-autocomplete-light 默认加载以前保存的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926940/

相关文章:

jquery - 使用 jQuery 修改@media 打印

javascript 和 django

python - 使用 Selenium 进行 IP 欺骗/购买共享代理?

python - Tornado websockets : share open web sockets between processes

javascript - 在 jQuery .load Ajax 之后执行 if 语句

python - 条件 SkipTo+可选匹配

Python,递归应用正则表达式负向前瞻

javascript - Angular -Js $http.post 在 Django 中不起作用

python - 基于跨关系的查找将选择限制为外键

javascript - 从下拉列表中选择多个值并调用 javaScript 函数