question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Duplicated select2 input when rendering

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:15 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
codingjoecommented, Nov 3, 2020

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.

1reaction
jpm92commented, Nov 3, 2020

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 🎉

Read more comments on GitHub >

github_iconTop Results From Across the Web

Forms with Select2 are duplicated when clicking back button ...
Looks more like a rendering issue. I don't think you should worry about what users see if they press the back button after...
Read more >
Select2 doesn't work with multiple <select> with same id #5501
A workaround is to remove the data-select2-id value of the subject select element. I guess this can be natively supported as it can...
Read more >
Select2 inside DIV not working correctly - Is this a bug?
I set up SELECT2 and am trying to use it inside a form, but it's not dispaying correctly. This is my HTML code:...
Read more >
Duplicate Topic Categories shown on the Case creation form
The case_creation UI page uses a third party jquery component select2 to render the HR Service field. The select2 input will paginate the...
Read more >
I want to duplicate my row with same value as when render
Value, "class": "select2-table select2-border border-primary ... SampleName", render: function (d, t, r, m) { var html = '<input ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found