Hi! I am working on an app that uses django-Select2
for dropdowns with search. I am able to get Select2
dropdowns working very well in a simple test page, but I am not able to get it working in my actual app page? I think the problem has to do with the <script>
tag location? (might be wrong…).
My template structure currently looks like the following (note: these are much simplified from actual, but I tried to maintain the relevant parts and relationships…):
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Select2 Drop-down lists, include jQuery first -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
<div class="max-w-screen-xl mx-auto p-4 ml-10">
<script>
// Initialize Select2
document.addEventListener('DOMContentLoaded', function () {
console.log('Select2 initialized');
$('.django-select2').select2();
});
</script>
{% block content %}
{% endblock %}
</div>
</body>
</html>
<!-- assemblies.html -->
{% extends 'base.html' %}
{% block content %}
<div id="assemblies-page">
<div id="assemblies-container">
<div id="assemblies-grid-container">
{% include 'assembly.html' %}
</div>
</div>
</div>
{% endblock %}
<!-- assembly.html -->
<div id="assembly">
{% if assembly %}
{% block assembly-detail-view %}
<div id="assembly-detail-view">
<div id="assembly-cells">
{% for layer, form in layers_and_forms %}
{% block layer %}
<div id="layer-{{ layer.pk }}">
<div id="cell-{{ cell.pk }}">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
</div>
{% endblock %}
{% endfor %}
</div>
</div>
{% endblock %}
{% endif %}
</div>
Given the above, I get all the expected form elements on the page, but they are not Select2
styled, they are just normal dropdown menus:
If I investigate the form element, it does appear to be properly tagged as a django-select2
element:
but it is not getting any of the actual behavior or styling applied? Which I assume is due to an error in how I have the <script>
inserted?
So:
- Am I correct that this is due to the tag?
- Where should the be inserted, assuming the template structure shown above?
thank you so much for any thoughts or suggestions!
best,
@ed-p-may