I'm having a problem with a simple task I want to accomplish. I want to load a list of models and when a user clicks on a button, I want to edit two fields of the selected instance of a model.
I leave my model:
class Enfermos(models.Model):
TIPO_ANIMAL = [
('terneros', 'Terneros'),
('terneras', 'Terneras'),
('vaquillas', 'Vaquillas'),
('toros', 'Toros'),
('vacas_viejas', 'Vacas Viejas'),
]
tipo = models.CharField(choices=TIPO_ANIMAL, max_length=20)
potrero = models.ForeignKey('campo.Potrero', on_delete=models.DO_NOTHING)
enfermedad = models.ForeignKey('Enfermedad', on_delete=models.DO_NOTHING)
fecha = models.DateTimeField(default=timezone.now)
descripcion = models.CharField(null=True, blank=True, max_length=80, help_text='Si considera necesario agregar alguna descripción del animal enfermo aquí lo puede hacer. De lo contrario dejar vacio.')
ESTADO = [
('curado', 'curado'),
('muerto', 'muerto'),
('enfermo', 'enfermo'),
]
estado = models.CharField(choices=ESTADO, max_length=10, default='enfermo')
def __str__(self):
return 'Un ' + self.tipo + ' con: ' + self.enfermedad.nombre_enfermedad
The significant part of my template:
<div class="container" style="min-height: 100%;height: 100%;">
<div class="row justify-content-center">
<div class="col-10">
<div class="py-3">
<h2>Panel de gestion de animales enfermos</h2></div>
{% for e in enfermos %}
<div class="row" style="border: double; margin-bottom: 20px; padding: 10px;">
<div class="col-8">
<h3>{{ e }}</h3>
<span id="enfermo_{{ e.id }}" style="display: none;">{{ e.id }}</span>
</div>
<div class="col-2">
<button data-enfermo-id="{{ e.id }}" type="button" class="btn btn-primary c_curo">Curado</button>
</div>
<div class="col-2">
<button data-enfermo-id="{{ e.id }}" type="button" class="btn btn-danger c_murio">Muerto</button>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{# aca viene magia de jquery, necesaria porque django no tiene frontend :( #}
<script>
$(".c_curo").on("click", function (e) {
e.preventDefault();
var url = "{% url 'animal:curar-enfermo' %}";
var e_id = '#enfermo_'+$(this).attr('data-enfermo-id');
var enfermo_id = $(e_id).text();
console.log(enfermo_id);
$.ajax({
url: url,
data: {
'enfermo': enfermo_id
},
success: function (data) {
console.log(data)
}
});
});
</script>
The view:
def curarEnfermo(request):
enfermo_id = request.GET.get('enfermo')
enfermo = Enfermos.objects.get(id=enfermo_id)
enfermo.estado = 'curado'
enfermo.fecha = timezone.now
enfermo.save()
return JsonResponse({'success': 'true'})
And the related url:
path('ajax/enfermedad/curar', views.curarEnfermo, name='curar-enfermo'),
If I run it on debugger mode, everything seems to work flawlessly up to the saving point. The instance of the model is retrieved and the fields are edited but when running the enfermo.save() instruction (on the view) an internal server error is triggered and it says to be:
TypeError at /ajax/enfermedad/curar expected string or bytes-like object