In A django App I want to return a message from views and show it using toast. and my main page is:
<div class="toast-container p-3">
<div id="toast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div id="toast-body" class="toast-body"></div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
</div>
</div>
<div class="col-md-3">
<div id="Chamber_list">
{% if messages %}
{% for message in messages %}
{% if message.tags == 'error' %}
<div class="alert alert-danger" style="...">{{ message }}</div>
{% else %}
<div class="alert alert-success" style="...">{{ message }}</div>
{% endif %}
{% endfor %}
{% endif %}
{% include 'Home/MOG_Division/rooms/Detaile/Chamber_list.html' %}
</div>
</div>
And this is my views.py code
> def edit_actl(request, pk):
theroom = get_object_or_404(room_actual, pk=pk)
form_erAO = False
if request.method == "POST":
form = room_actualForm(request.POST, instance=theroom)
try:
if form.is_valid():
form.save()
response_data = {'success': True,'message': 'Room updated successfully'}
response = HttpResponse(json.dumps(response_data), content_type='application/json',status=204)
response['HX-Trigger'] = json.dumps({"roomListChanged": None, "showMessage": f"{theroom.room} {theroom.first_name} updated." })
return response
except ValueError:
form_erAO = 'Check your input dates'
response_data = {'error': True, 'message': 'Room Already Occupied, Try another range'}
response = HttpResponse(json.dumps(response_data), content_type='application/json',status=204)
response['HX-Trigger'] = json.dumps({"roomListChanged": None, "showMessage":'Try another range'})
return response
else:
form = room_actualForm(instance=theroom)
return render(request, 'Home/MOG_Division/rooms/Detaile/Actul_form.html', {
'form': form,
'theroom': theroom,
'form_erAO' : form_erAO
})
and this is my form html page:
<form method="post" id="yourFormId" hx-post="{{ request.path }}" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' class="modal-content">
<div class="col-sm-12">
<div class="form-group row">
<div class="col-sm-4">{{ form.as_p }}</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
<button type="submit" class="btn btn-primary">Enregistrer</button>
</div>
</form>
<script>
document.getElementById('yourFormId').addEventListener
('submit', function(event)
{
event.preventDefault();
var form = event.target;
var formData = new FormData(form);
fetch(form.action, {
method: form.method,
body: formData,
headers: {
'X-CSRFToken': '{{ csrf_token }}',
},
})
.then(response => {
console.log('Raw Response:', response.text());
return response.json();
})
.then(data => {
handleResponse(data);
})
if (data.error) {
document.getElementById('toast').classList.remove('bg-danger');
document.getElementById('toast').classList.add('bg-danger');
}
else {
document.getElementById('toast').classList.remove('bg-success');
document.getElementById('toast').classList.add('bg-success');
}
var toast = new bootstrap.Toast(document.getElementById('toast'));
toast.show()
})
</script>
the problem is that I need to change the color of the message when it is error. the Javascript didn't work when I use ;
if (data.error) {
document.getElementById('toast').classList.remove('bg-danger');
document.getElementById('toast').classList.add('bg-danger');
}
else {
document.getElementById('toast').classList.remove('bg-success');
document.getElementById('toast').classList.add('bg-success');
}
but when
I set it without if (data.error) it gives me a toast message in red
document.getElementById('toast').classList.remove('bg-danger');
document.getElementById('toast').classList.add('bg-danger');
have you any solution?
Django has the messages framework built in. Just use that - it will save you a lot of headaches :)
https://docs.djangoproject.com/en/5.0/ref/contrib/messages/