[Answer]-Recent values in CharField

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.

👤Erik

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>

Leave a comment