<select class="form-select" name="{{ key }}{{ field.multiple and '[]' }}" id="{{ 'form-select-'+key }}" {{ field.multiple and 'multiple' }}>
    {% for val, name in field.options.items() %}
        <option value="{{ val }}" {% if (field.multiple and val in value) or (not field.multiple and val == (value and (value.pk or value))) %}selected{% endif %}>
            {{ name }}
        </option>
    {% endfor %}
</select>
{% if help_text %}
    <div class="mt-2">
        <small class="form-hint">{{ help_text }}</small>
    </div>
{% endif %}
<script src="/statics/vendor/cookie.min.js"></script>
<script>
    var $select{{key}} = $('select#form-select-{{key}}')
    var conf = {minimumResultsForSearch: 25, width: '100%'}
    if ("{{ field.source_field}}") {
        conf['ajax'] = {
            url: '/v2/{{ field.source_field}}',
            dataType: 'json',
            headers: {"Authorization" : 'Bearer '+Cookies.get('token'), "content-type": "application/json"},
            data: function (params) {
              var query = {
                q: params.term,
                page: params.page || 1
              }
              return query;
            },
            cache: true
        }
    }
    if ("{{ field.multiple}}") {
        conf['ajax']['processResults'] = function (data, params) {
          if (!$select{{key}}.select2('data').length) {
           $.each(data.results, function(index, value) {
            if (value.selected) {
                if ($select{{key}}.find("option[value='" + value.id + "']").length) {
                    $select{{key}}.val(value.id);
                } else {
                    var option = new Option(value.text, value.id, true, true);
                    $select{{key}}.append(option);
                }
            }
           });
           $select{{key}}.trigger('change');
          }
          return data;
        }
{#        conf['ajax']['url'] +=#}
    }
    $select{{key}}.select2(conf)
</script>