I am trying to create a dropdown of countires which can be searchable based on this doc, however almost disappointed to find any solution by googling.
I am using django-cities-light
package and django-autocomplete-light, and all I need to do is creating a field of countries/cities and populating it in a form and making it searchable,
in setting.py and installed apps:
INSTALLED_APPS = [
'dal',
'dal_select2',
'app.apps.MyownAppConfig',
'users.apps.UsersConfig',
'crispy_forms',
'tinymce',
'cities_light',
'django.contrib.admin',
'django.contrib.auth',
...
]
in models.py:
from tinymce.models import HTMLField
from cities_light.models import Country
class Post(models.Model):
...
descript = HTMLField(blank=True, null=True)
location = models.ForeignKey(Country, blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
in views.py:
class CountryAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Country.objects.none()
qs = Country.objects.all()
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
In forms.py:
class postform(forms.ModelForm):
class Meta:
model = Post
fields ='__all__'
exclude = ['date_published']
widgets = {
'location': autocomplete.ModelSelect2(url='country-autocomplete' , attrs={'data-placeholder': 'select location...', 'data-minimum-input-length': 4})
}
search_fields = ['name']
and in postform.html:
{% extends "app/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<main>
<form id="dropdownForm" method="POST" action="" enctype="multipart/form-data">
<fieldset class="form-group">
{% csrf_token %}
<div class="content-section">
{{ form.descript }}
<label>location</label>
{{ form.location }}
</div>
</fieldset>
</form>
</main>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
{{ form.media }}
{% endblock content %}
and in url.py:
urlpatterns = [path('country-autocomplete/', CountryAutocomplete.as_view(model=Country), name='country-autocomplete')]
But what I get is this:
Moreover, in terminal I see this msg:
"GET /static/vendor/select2/dist/css/select2.css HTTP/1.1" 404 1832
I also had a look to all available questions in SO, including this one, but didn't help that much. Could you please help me with this problem a bit?