Hide modal after form successful submition

I'm using Bootstrap Modals and HTMX to create an event in Django. I got the form rendering OK inside the modal, but when I submit the form the index page appears inside the modal (the success_url parameter of the CreateView). I'd like to hide the modal after the submission and then show the index full screen.

This is the modal in the template:

<!-- Start modal -->
<button type="button" hx-get="{% url 'events:create' %}" hx-target="#eventdialog" class="btn btn-primary">
    Add an event
</button>
<div id="eventmodal" class="modal fade" tabindex="-1">
    <div id="eventdialog" class="modal-dialog" hx-target="this">
    </div>
</div>
<!-- End modal -->

And this is the Javascript that makes it show the modal:

;(function(){
    const modal = new bootstrap.Modal(document.getElementById('eventmodal'))

    htmx.on('htmx:afterSwap', (e) => {
        if (e.detail.target.id == "eventdialog")
        modal.show()
    })

I tried adding this to the Javascript code but it doesn't work:

htmx.on('htmx:beforeSwap', (e) => {
    if (e.detail.target.id == 'eventdialog' && !e.detail.xhr.response)
    modal.hide()
})

How can I make the modal hide after submitting the form? This is my view:

class CreateEvent(LoginRequiredMixin, CreateView):
    model = Event
    form_class = EventForm
    template_name = 'events/events_form.html'
    success_url = reverse_lazy('events:index')

def form_valid(self, form):
    form.instance.author = self.request.user
    event_obj = form.save(commit=True)
    image = self.request.FILES.get('image')
    if image:
        EventImage.objects.create(title=event_obj.title, image=image, event=event_obj)
    return super(CreateEvent, self).form_valid(form)
Back to Top