Hello
I need to open a madal with a form inside and i need that the fields are filled getting data from a db.
I have proceed as follow:
Crate a button that open the modal and call a function:
part of template
<button class="btn btn-primary mb-2 mt-2 ml-2 mr-2" onclick="mod_cli_mod.showModal()" hx-get="{% url 'mod_cli' dati.idclienti %}" >Modifica cliente</button></td>
Now the function in the views file is
def mod_cli(request, idclienti):
tutto = Clienti.objects.get(pk=idclienti)
print('il cliente è: ',idclienti)
form = ClientiForm(initial={'iban': tutto.iban, 'idclienti': tutto.idclienti, 'sdi': tutto.sdi, 'piva': tutto.piva,
'ragione': tutto.ragione, 'via': tutto.via, 'cap': tutto.cap, 'citta': tutto.citta,
'prov': tutto.prov, 'stato': tutto.stato, 'persona': tutto.persona, 'tel': tutto.tel,
'cell': tutto.cell, 'email': tutto.email})
print('passato')
response = render(request,'polls/partial/mod_cli_mod.html', {'form': form,'idclienti': tutto.idclienti})
response['HX-Retarget'] = '#mod_cli_mod'
response['HX-Reswap'] = 'outerHTML'
return response
Then the odal is as follow:
<dialog id="mod_cli_mod" class="modal">
<div class="modal-box">
<h3 class="font-bold text-lg mb-4">{{ idclienti }} titolo </h3>
<form
hx-post="{% url 'tutti_clienti' %}"
hx-target='#contact-table-body'
hx-swap="afterbegin"
class="mb-4">
{% csrf_token %}
<div class="form-control w-full">
<label class="label">
<span class="label-text">Ragione Sociale</span>
{{ form.ragione}}
{% if form.ragione.errors %}
<label class="label text-error">
{{form.ragione.errors}}
</label>
{% endif %}
</div>
<div class="modal-action">
<button type="button" class="btn"
onclick="mod_cli_mod.close()">Cancella</button>
<button type="submit" class="btn btn-primary">Salva Modifiche</button>
</div
></form>
</div>
</dialog>
My problem is that the first time I call the function, the modal is shown with all the fields empty. From the second time I push the button, the fields are not empty. However, in both cases, the modal is automatically closed after a few seconds.
And if I change the selection, for example, to another row of the table, the first time i get the data of the previously selected row, starting from the second click i get the correct data.
Any idea
Many Thanks