Search code examples
jquerydjangoautocompletedjango-autocomplete-light

Autocomplete field not rendering in django-autocomplete-light formset


I'm trying to autocomplete a foreign key field, but I am following the steps in the documentation and cannot get it to work .

Views:

class ProductoAutocomplete(autocomplete.Select2QuerySetView):
 def get_queryset(self):
    qs = Producto.objects.all()
    if self.q:
        qs = qs.filter(nombre__icontains=self.q)
    return qs

Urls:

 url(r'^producto-autocomplete/$',ProductoAutocomplete.as_view(),name='producto-autocomplete',),

and the result is correct:

Result in image

Forms:

class DetalleForm(forms.ModelForm):
 class Meta:
    model = DetalleVenta
    fields = [
        'producto',
        'cantidad',
        'preciounit',
        'subtotal',
    ]
    labels = {
        'producto':'Producto',
        'cantidad':'Cantidad',
        'preciounit':'Prec.Unit.',
        'subtotal':'Subtotal',
    }
    widgets = {
        'producto':forms.Select(attrs={'class':'form-control', 'autofocus':True}),
        'producto': autocomplete.ModelSelect2(url='producto-autocomplete', attrs={'data-placeholder': 'Royal ...', 'data-minimum-input-length': 2}),
        'cantidad':forms.NumberInput(attrs={'class':'form-control cantidad'}),
        'preciounit':forms.NumberInput(attrs={'class':'form-control'}),
        'subtotal':forms.NumberInput(attrs={'class':'form-control subtotal', 'readonly':True}),
    }
DetalleFormSet = inlineformset_factory(Venta, DetalleVenta,
                                   form=DetalleForm, extra=1)

Template:

 {% extends 'base/base.html' %}
 {% load static %}
 {% block titulo%} Registrar venta {%endblock%}
 {% block contenido %}
<div class="col-md-12">
<form method="post">{% csrf_token %}
    <div class="col-md-4 form-group">
    <label class="font-weight-bold" for="{{form.cliente.name}}">{{form.cliente.label}}</label>
    {{form.cliente}}
    </div>
    <h4 class="text-left">Detalle de venta: </h4>
    <div class="table-responsive-sm">
        <table class="table" id="tablaDetalle">
            {{ detalleformset.management_form }}
            <thead class="thead-dark">
                <th>Producto</th>
                <th width="100px">Cantidad</th>
                <th width="115px">Prec.Unit.</th>
                <th width="115px">Subtotal</th>
                <th>Acción</th>
            </thead>
            <tbody>
            {% for form in detalleformset.forms %}
                <tr class="formset_row">
                    {% for field in form.visible_fields %}
                        <td>
                            {# Include the hidden fields in the form #}
                            {% if forloop.first %}
                                {% for hidden in form.hidden_fields %}
                                    {{ hidden }}
                                {% endfor %}
                            {% endif %}
                            {{ field.errors.as_ul }}
                            {{ field }}
                        </td>
                    {% endfor %}
                </tr>
            {% endfor %}
            </tbody>
        </table>
        </div>
        <div class="row justify-content-md-end">
        <div class="col-md-2">
        <label class="font-weight-bold" for="{{form.total.name}}">{{form.total.label}}</label>
        {{form.total}}
        </div>
        </div>
        <div class="form-group">
        <label class="font-weight-bold" for="{{form.descripcion.name}}">{{form.descripcion.label}}</label>
        {{form.descripcion}}
        </div>
        <div class="col-md-4 offset-md-4">
          <button class="btn btn-block btn-lg btn-primary" type="submit"><span><i class="fa fa-shopping-cart"></i>
          </span>Registrar venta</button>
        </div>
    </form>
    </div>
  {% endblock %}
  {% block javascript %}
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
{{ form.media }}
<script src="{% static 'js/jquery.formset.js' %}"></script>
<script type="text/javascript">
  $('.formset_row').formset({
        addText: 'Agregar Producto',
        deleteText: 'remover',
        prefix: 'detalleventa'
    });
        $("#tablaDetalle").on("focus keyup", "tr", function(){
          var total = 0;

          var row = $(this).closest("tr");
          var cantidad = parseInt(row.find("input:eq(2)").val());
          var precio = parseFloat(row.find("input:eq(3)").val());
          var subtotal = cantidad * precio;
          row.find("input:eq(4)").val(isNaN(subtotal) ? "" : subtotal.toFixed(2));

            $(".subtotal").each(function () {
                var stval = parseFloat($(this).val());
                total += isNaN(stval) ? 0 : stval;
            });

            $('.delete-row').click(function(){
                var $fila = $(this).parents('tr');
                var valsub = parseFloat($fila.find('input:eq(4)').val());
                new Promise(function(done){
                    total -= isNaN(valsub) ? 0 : valsub;
                    $('.total').val(total.toFixed(2));
                    done();
                })
                .then(function(){
                   $fila.find('input:eq(4)').val(0);
                })
            });

            $('.total').val(total.toFixed(2));
        });
  </script>   
  {% endblock %}

This does not render the autocomplete field, but just shows me an empty selection field.

Image demo

This is currently my problem, and I followed the steps in the documentation of django-autocomplete-light.

It's the first time I'm doing this in Django, and I cannot find the error. Maybe something is missing.


Solution

  • Resolved I should have passed the name of the form this way:

     {{ detalleformset.media }}