I have autocomplete code which does not work.
I have input field class Coordinate where when i type code it finds value from my DB that matches with geo_code and hence finds the input code country.
So when i type UK it matches with geo_code and then matches the last with the country so in this case UK is code i type it can be found in geo_code and country is United Kingdom. The code works, what i want to achieve is bring autocomplete to give suggestions while typing. for examples:
UK United Kingdom
USA United States of America
What i did so far:
In models.py i have:
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)
in 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')}
in 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
in 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>
in 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 %}
I would appreciate you help to solve this case.

