自动填充字段未在django-autocomplete-light formset

时间:2018-02-24 17:09:57

标签: jquery django autocomplete django-autocomplete-light

我尝试自动填写外键字段,但我按照文档中的步骤操作,无法使其工作。

查看:

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

的url:

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

,结果是正确的:

Result in image

表单:

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)

模板:

 {% 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 %}

这不会呈现自动填充字段,只是显示一个空的选择字段。

Image demo

这是我目前的问题,我按照documentation of django-autocomplete-light中的步骤进行了操作。

这是我第一次在Django中这样做,我找不到错误。也许缺少一些东西。

0 个答案:

没有答案