Skip to content

Using Bootstrap4 Popovers for select2 fields #247

@urzbs

Description

@urzbs

Goal
I am trying to add a Bootstap 4 Popover into a field that uses the ModelSelect2Widget
So when the field is hovered / focussed the popover will be displayed.

Problem
The popovers for select2 fields are not shown/triggered. (but visible in the html).
by removing {{ form.media.js }} they will be shown, but then i cant use the select2 features.

(Other fields e.g. CharField do work with this popover.)

Code Snippet

forms.py

from django import forms
from django_select2 import forms as s2forms

class UserPicker(s2forms.ModelSelect2Widget):
    search_fields = [
        "first_name__icontains",
        "last_name__icontains",
    ]

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["user"].widget.attrs.update({
            'data-html': 'true',
            'title': 'my title',
            'data-toggle': 'popover',
            'data-trigger': 'focus hover',
            'data-content': '<h1>Hello World</h1>',
            'data-placement': 'right',
        })

    class Meta:
        model = MyModel
        fields = ("user",  )
        widgets = {
            "user": UserPicker(),
        }

html template:

{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap 4 Popover Example</title>

    <!-- Add Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <!-- Select2 CSS -->
    <link rel="stylesheet" href="{% static 'select2/css/select2.css' %}">

    <!-- Add jQuery (required for Bootstrap's JavaScript plugins) -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <!-- Add Popper.js (required for Bootstrap's JavaScript plugins) -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>

    <!-- Add Bootstrap JS -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
    {{ form|crispy }}
    {{ form.media.js }}
    
    <style>
      .select2-container {
          width: 100% !important;
      }
      .select2-selection {
          height: 40px !important;
          line-height: 40px !important;
      }
    </style>

    <!-- Initialize the popover with JavaScript -->
    <script>
        $(document).ready(function(){
            $('[data-toggle="popover"]').popover();
        });
    </script>
</body>
</html>

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions