自动完成什么都不做。怎么了?
Autocomplete does nothing. What is wrong?
我的自动完成代码不起作用。
我有输入字段 class 坐标,当我键入代码时,它从我的数据库中找到与 geo_code 匹配的值,从而找到输入代码国家/地区。
所以当我键入 UK
时,它与 geo_code
匹配,然后将最后一个与 country
匹配,所以在这种情况下,UK 是我键入的代码,它可以在 geo_code 国家是英国。代码有效,我想要实现的是在输入时自动完成以提供建议。例如:
UK United Kingdom
USA United States of America
到目前为止我做了什么:
在models.py我有:
class Coordinate(models.Model):
code = models.CharField(max_length=150)
class Profiles(models.Model):
geocode=models.CharField(max_length=200)
country=models.CharField(max_length=500)
city=models.CharField(max_length=500)
class Meta:
managed=False
db_table='profiles_country'
def __str__(self):
return '{}'.format(self.geocode)
在forms.py:
from dal import autocomplete
class CoordinateForm(forms.ModelForm):
code= forms.CharField(max_length=150, label='',widget= forms.TextInput)
class Meta:
model = Coordinate
fields = ('__all__')
widgets = {
'code': autocomplete.ModelSelect2(url='coordinate-autocomplete')}
在views.py:
class CoordinateAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Profiles.objects.none()
qs = Profiles.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
在base.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static 'geoproj/css/main.css' %}">
</head>
<body>
<div>{% block content %}{% endblock %}
{% block javascripts %} {% endblock %} </div>
</body>
</html>
在geo.html中:
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form enctype="multipart/form-data" method="POST" >
{% csrf_token %}
{{ form}}
{{form.media }}
<button class = "btn btn-primary" type="submit">OK</button></form>
{% endif %}
{% endblock content %}
{% block javascripts %} {% endblock %}
如果你能帮助解决这个问题,我将不胜感激。
我没有看到链接 URL 响应和 HTML 模板的 js。在这里我将如何解决它。如果您的观点有效。
您将通过
生成建议
- 首先创建一个js事件监听器从输入框获取文本
表格
- 收到此文本后,您将 ajax 调用视图 URL
你提到了
- 获得 ajax 结果后,您将为
循环并为输入生成 select 个标签。
这就是我编写与 Html 模板和 Django 自动完成视图通信的 js 代码的方式 URL。
code
CoordinateForm 中的字段是 CharField,而不是 ModelChoiceField,因此它无法正确处理自动完成返回的 QuerySet。
models.py:
class Coordinate(models.Model):
code = models.CharField(max_length=150)
def __str__(self):
return self.code
class Profiles(models.Model):
geocode=models.CharField(max_length=200)
country=models.CharField(max_length=500)
city=models.CharField(max_length=500)
class Meta:
managed=False
db_table='profiles_country'
def __str__(self):
return '{}'.format(self.geocode)
views.py:
def geoview(request):
if request.method == "POST":
#do your operations
return render(request, 'result.html')
return render(request, 'index.html')
def getgeocode(request, geocode):
results = Coordinate.objects.filter(code__istartswith=str(geocode))
sendres = ""
for resn in results[:10]:
sendres += "<option class='bg-primary'>" + resn.code + "</option>"
return HttpResponse(sendres)
index.html:
{% extends 'base.html' %}
{% block content %}
<form enctype="multipart/form-data" method="POST">
<input type="text" list="mylist" name="geocodes" id="geocodes" placeholder="enter geocde"
onkeyup="getGeoCode(this.value)" autocomplete="off"/>
<datalist id="mylist">
</datalist>
<button class="btn btn-primary" type="submit">OK</button>
</form>
{% endblock content %}
{% block javascripts %}
<script>
function getGeoCode(str) {
if (str.length == 0) {
document.getElementById("mylist").innerHTML = "";
document.getElementById("mylist").style.border = "0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("mylist").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "/coordinate-autocomplete/" + str, true);
xmlhttp.send();
}
</script>
{% endblock javascripts %}
urls.py:
from django.urls import path
from app import views
urlpatterns = [
....
path('geo/', views.geoview, name='geo'),
path('coordinate-autocomplete/<geocode>', views.getgeocode, name='coordinate-autocomplete'),
....
]
并且您可以确认它在您的终端中工作,您将看到如下请求:
/coordinate-autocomplete/{word_in_iput}
[17/Apr/2020 16:19:52] "GET /coordinate-autocomplete/u HTTP/1.1" 200 120
[17/Apr/2020 16:20:03] "GET /coordinate-autocomplete/us HTTP/1.1" 200 65
[17/Apr/2020 16:20:06] "GET /coordinate-autocomplete/u HTTP/1.1" 200 120
[17/Apr/2020 16:20:13] "GET /coordinate-autocomplete/i HTTP/1.1" 200 44
我的自动完成代码不起作用。
我有输入字段 class 坐标,当我键入代码时,它从我的数据库中找到与 geo_code 匹配的值,从而找到输入代码国家/地区。
所以当我键入 UK
时,它与 geo_code
匹配,然后将最后一个与 country
匹配,所以在这种情况下,UK 是我键入的代码,它可以在 geo_code 国家是英国。代码有效,我想要实现的是在输入时自动完成以提供建议。例如:
UK United Kingdom
USA United States of America
到目前为止我做了什么:
在models.py我有:
class Coordinate(models.Model):
code = models.CharField(max_length=150)
class Profiles(models.Model):
geocode=models.CharField(max_length=200)
country=models.CharField(max_length=500)
city=models.CharField(max_length=500)
class Meta:
managed=False
db_table='profiles_country'
def __str__(self):
return '{}'.format(self.geocode)
在forms.py:
from dal import autocomplete
class CoordinateForm(forms.ModelForm):
code= forms.CharField(max_length=150, label='',widget= forms.TextInput)
class Meta:
model = Coordinate
fields = ('__all__')
widgets = {
'code': autocomplete.ModelSelect2(url='coordinate-autocomplete')}
在views.py:
class CoordinateAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Profiles.objects.none()
qs = Profiles.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
在base.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static 'geoproj/css/main.css' %}">
</head>
<body>
<div>{% block content %}{% endblock %}
{% block javascripts %} {% endblock %} </div>
</body>
</html>
在geo.html中:
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form enctype="multipart/form-data" method="POST" >
{% csrf_token %}
{{ form}}
{{form.media }}
<button class = "btn btn-primary" type="submit">OK</button></form>
{% endif %}
{% endblock content %}
{% block javascripts %} {% endblock %}
如果你能帮助解决这个问题,我将不胜感激。
我没有看到链接 URL 响应和 HTML 模板的 js。在这里我将如何解决它。如果您的观点有效。
您将通过
- 首先创建一个js事件监听器从输入框获取文本 表格
- 收到此文本后,您将 ajax 调用视图 URL 你提到了
- 获得 ajax 结果后,您将为 循环并为输入生成 select 个标签。
这就是我编写与 Html 模板和 Django 自动完成视图通信的 js 代码的方式 URL。
code
CoordinateForm 中的字段是 CharField,而不是 ModelChoiceField,因此它无法正确处理自动完成返回的 QuerySet。
models.py:
class Coordinate(models.Model):
code = models.CharField(max_length=150)
def __str__(self):
return self.code
class Profiles(models.Model):
geocode=models.CharField(max_length=200)
country=models.CharField(max_length=500)
city=models.CharField(max_length=500)
class Meta:
managed=False
db_table='profiles_country'
def __str__(self):
return '{}'.format(self.geocode)
views.py:
def geoview(request):
if request.method == "POST":
#do your operations
return render(request, 'result.html')
return render(request, 'index.html')
def getgeocode(request, geocode):
results = Coordinate.objects.filter(code__istartswith=str(geocode))
sendres = ""
for resn in results[:10]:
sendres += "<option class='bg-primary'>" + resn.code + "</option>"
return HttpResponse(sendres)
index.html:
{% extends 'base.html' %}
{% block content %}
<form enctype="multipart/form-data" method="POST">
<input type="text" list="mylist" name="geocodes" id="geocodes" placeholder="enter geocde"
onkeyup="getGeoCode(this.value)" autocomplete="off"/>
<datalist id="mylist">
</datalist>
<button class="btn btn-primary" type="submit">OK</button>
</form>
{% endblock content %}
{% block javascripts %}
<script>
function getGeoCode(str) {
if (str.length == 0) {
document.getElementById("mylist").innerHTML = "";
document.getElementById("mylist").style.border = "0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("mylist").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "/coordinate-autocomplete/" + str, true);
xmlhttp.send();
}
</script>
{% endblock javascripts %}
urls.py:
from django.urls import path
from app import views
urlpatterns = [
....
path('geo/', views.geoview, name='geo'),
path('coordinate-autocomplete/<geocode>', views.getgeocode, name='coordinate-autocomplete'),
....
]
并且您可以确认它在您的终端中工作,您将看到如下请求:
/coordinate-autocomplete/{word_in_iput}
[17/Apr/2020 16:19:52] "GET /coordinate-autocomplete/u HTTP/1.1" 200 120
[17/Apr/2020 16:20:03] "GET /coordinate-autocomplete/us HTTP/1.1" 200 65
[17/Apr/2020 16:20:06] "GET /coordinate-autocomplete/u HTTP/1.1" 200 120
[17/Apr/2020 16:20:13] "GET /coordinate-autocomplete/i HTTP/1.1" 200 44