在自动填充表单中创建新选项时,Django自动完成轻松POST 4次

时间:2016-08-23 04:12:02

标签: django python-3.x autocomplete django-autocomplete-light

我创建了这个模型:

class TitleDescriptionLazyModel(models.Model):

class Meta:
    abstract = True

title = models.CharField(max_length=255)
description = models.TextField(blank=True)

def __str__(self):
    return self.title

class Jobsite(TitleDescriptionLazyModel):
    pass

在文档(views.py)中描述的自动完成视图中使用了哪个:

class JobsiteAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):

def get_queryset(self):
    if not self.request.user.is_authenticated():
        return Jobsite.objects.none()

    qs = Jobsite.objects.all()

    if self.q:
        qs = qs.filter(title__istartswith=self.q)

    return qs

和我的urls.py将标题字段设置为“create_field”:

urlpatterns = [
    JobsiteAutocomplete.as_view(create_field='title'), name='jobsite_autocomplete'),
]

但是当我运行它时,我得到自动完成视图传递获取请求,直到我点击创建按钮,此时它发布4次,当我希望它创建1时,在数据库中创建4个新项目:

> [22/Aug/2016 20:44:04] "GET /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 356
[22/Aug/2016 20:44:10] "GET /worklogs/jobsite-autocomplete/?q=som HTTP/1.1" 200 252
[22/Aug/2016 20:44:11] "GET /worklogs/jobsite-autocomplete/?q=some HTTP/1.1" 200 254
[22/Aug/2016 20:44:12] "GET /worklogs/jobsite-autocomplete/?q=somewhere HTTP/1.1" 200 116
[22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31
[22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31
[22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31
[22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31

it creates 4 every time... why?

django = 1.9 python = 3.4 django-autocomplete-light(3.1.8)

2 个答案:

答案 0 :(得分:0)

我使用的是jQuery v1.11.3

我升级到jQuery 2.2.4,它按预期工作。

答案 1 :(得分:0)

问题中也回答了这个问题。 https://github.com/yourlabs/django-autocomplete-light/issues/758#issuecomment-329814124

当你的页面中有多个select2.js时会发生这种情况。

在我的情况下,我使用了脆弱的表单,我也在页面上{{form.media}}删除了变量{{form.media}}它运行良好