django-select2: Duplicated select2 input when rendering

Looking at so many uncommented issues makes me not very hoping of fixing it anytime soon, but I’m facing a problem that I can’t seem to figure out. The select2 input is rendered twice, I get two search fields, specifically two of these:

<span class="select2 select2-container select2-container--default" dir="ltr" data-select2-id="1" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1" aria-disabled="false" aria-labelledby="select2-id_form-0-producto-container"><span class="select2-selection__rendered" id="select2-id_form-0-producto-container" role="textbox" aria-readonly="true"><span class="select2-selection__placeholder">Busque productos</span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

Captura de pantalla de 2020-10-30 11-14-35

This is my django code:

models.py
class Producto(models.Model):

    nombre_amistoso = models.CharField(
        max_length=40,
        help_text=_('Nombre amigable del producto.')
    )
    nombre_fabricante = models.CharField(
        max_length=60,
        help_text=_(
            'Nombre real del producto, tal como lo conoce el fabricante.'
        )
    )
    fabricante = models.ForeignKey(
        'Fabricante',
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    referencia = models.CharField(
        max_length=25,
        help_text=_('Referencia del fabricante.')
    )

forms.py
class ProductoWidget(s2forms.ModelSelect2Widget):
    """ Widget especial creado con libreria django-select2.
    Busca según los campos especificados en serach_fields. """

    search_fields = [
        "nombre_amistoso__icontains",
        "nombre_fabricante__icontains",
        "referencia__icontains",
    ]


class ArticuloForm(forms.ModelForm):
    """ Este formulario se utiliza para agregar articulos a la pizarra. """

    class Meta:
        model = Articulo
        fields = ['producto', 'unidades']
        widgets = {
            "producto": ProductoWidget(
                {'data-language': 'es',
                 'data-placeholder': 'Busque productos',
                 'data-width': '100%',
                 }
            ),
        }

views.py

def NuevaNota(request):
    ArticuloFormset = formset_factory(ArticuloForm)
    if request.method == "POST":
    # bunch of code

    else:
        articulos = ArticuloFormset()
        nota = NotaForm()
        context = {
            'articulos': articulos,
            'nota': nota
        }
        return render(request, "gestion/anotar.html", context)

The inputs work perfectly, they search in the fields they have to. Only they render in duplicate. Also, the data-language attribute seems to not be taking any effect (still in english).

I hope @codingjoe can take a look at the open issues anytime soon. Thanks a lot for taking over, let me know If I can be helpful in any manner, I’d love to. J.

update: I add also the html template.

base_generic.html

  <head>
    {% load static %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Favicon -->
    <link rel="icon" href="{% static '/img/favicon.ico' %}">
    <!-- CSS links -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
          crossorigin="anonymous">
    <!-- Iconos FontAwesome -->
    <link rel="stylesheet" type="text/css" href="{% static 'gestion/css/styles.css' %}">
    {% block extracss %}{% endblock %}
    <script src="https://kit.fontawesome.com/434ec950ab.js" crossorigin="anonymous"></script>
    <!-- - -->
    <title>{% block titulo %}Gestión de pedidos TERSTEM{% endblock %}</title>
  </head>
  <body>
    ...
    <!-- JS Scripts -->
    {% block jquery %}
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
            integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossorigin="anonymous"></script>
    {% endblock %}
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
            crossorigin="anonymous"></script>
    {% block extrajs %}{% endblock %}
    <!-- - -->
  </body>

anotar.html

{% extends "base_generic.html" %}
{% block extracss %}
  {{ articulos.media.css}}
{% endblock %}
{% block titulo %}Nueva nota | PEDIDOS TERSTEM{% endblock %}

{% block contenido %}
<form>
  {% csrf_token %}
    {{ articulos.management_form }}
  <div class="form-group">
    {% for articulo in articulos %}
        {{ articulo.as_p }}
    {% endfor %}
  </div>
  <div class="form-group">
    {{ nota.entrega }}
  </div>
</form>
{% block jquery %}
  <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
{% endblock %}
{% block extrajs %}
  {{ articulos.media.js }}
{% endblock %}
{% endblock %}

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (1 by maintainers)

Most upvoted comments

Wow, cool, thanks @CleitonDeLima for sorting this out. I love it when problems solve themselves, still I am sorry took me so long to answer. I kind of got married this weekend, and therefore was preoccupied.

In case this helps someone: obviously it was my fault. I opened a block before closing the previous one in the django template. I basically nested by mistake one block inside another (which is not how django works). Big thanks to @CleitonDeLima who reviewed my code and pointed it out 🎉

Yes it is, I’ll make you a collaborator, thanks 👍

@jpm92 How is your code to add forms to the formset?

As it is a formset, how is your empty_form in the template? I say this because select2 may be initializing 2x, once for empty_form and once when adding the new form, check this out for me.

I had this problem here