1đź‘Ť
models.py
class Mod(models.Model):
CHOICE_1 = 'CHOICE 1'
CHOICE_2 = 'CHOICE 2'
FIELD_CHOICES = (
(CHOICE_1, 'The real charfield value'),
(CHOICE_2, 'another charfield value')
)
f = models.CharField(
max_length=10,
choices=FIELD_CHOICES,
default=CHOICE_1
)
forms.py
class ModForm(ModelForm):
class Meta:
model = Mod
fields = ('f',)
end of views.py
return render(request, 'template.html', context={'mod_form': mod_form})
template.html
{{mod_form.as_p}}
This is extracted from working code. Hopefully the obfuscating my specific app out did not make it unclear.
0đź‘Ť
Autocomplete is a simple and nice solution. Thanks to Bilou06.
So, first of all we need to pass list of values, we can do it in view:
args['f_vals'] = Mod.objects.all().values_list("f", flat=True).distinct()[:10]
here we get all flat list of values and perform distinct to filter only uniq values. Then we limit values to 10. Additional benefit here is that we can perform more complex querysets with additional filtering and so on. For example if you have some field you can order it to be real “recent”. (You can edit this answer to provide some example).
Next we pass our args into template, and there create autocompleate:
<script>
$(document).ready(function(){
$("#id_f").autocomplete({
source: [{% for v in f_vals %}
"{{v}}",
{% endfor %}
],
minLength: 0,
}).on("focus", function () {
$(this).autocomplete("search", '');
});
}
</script>
On focus event here displays list of recent values immidiately on focus. Also values will be filtered when you typing.
Note that you should include jquery-ui:
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/jquery-ui.min.js' %}"></script>
- [Answer]-Several Django signal receivers in one module
- [Answer]-Django how to not use cached queryset while iterating?
- [Answer]-How to use foreign key to get related objects?
- [Answer]-Breaking form fields up separately django