Show chekbox in django marked when instantiating a form

I have the following code: views.py def actualizar_rutina(request, id_rutina): if not request.user.es_entrenador: messages.error(request, 'Usted no tiene permisos para acceder a esta pagina') return redirect('mostrar_rutina')

if request.method == 'GET':
    rutina = get_object_or_404(Rutina, id=id_rutina)
    
    rutinaform = RutinaForm(instance=rutina)

    contexto = {
        "rutinaform": rutinaform,
    }
    return render(request, 'core/crear_rutina.html', contexto)
else:
    return HttpResponse('no se pudo actualizar')

Models.py

DIAS_SEMANA = [
    ('LUN', 'Lunes'),
    ('MAR', 'Martes'),
    ('MIE', 'Miércoles'),
    ('JUE', 'Jueves'),
    ('VIE', 'Viernes'),
    ('SAB', 'Sábado'),
    ('DOM', 'Domingo'),
]

    class Rutina(models.Model):
        nombre = models.CharField(blank=False)
        dias_entrenamiento = models.CharField(blank=True)
        dias_descanso=models.CharField(blank=True)
        duracion_rutina = models.DurationField(default=datetime.timedelta(days=30), blank=True)
        
        def __str__(self):
            return self.nombre

form.py

class RutinaForm(forms.ModelForm):
    class Meta:
        model = Rutina
        exclude = ('dias_descanso',)

    dias_entrenamiento = forms.MultipleChoiceField(
        choices=DIAS_SEMANA,
        widget=forms.CheckboxSelectMultiple(),
        required=False
    )

What happens is that when I instantiate the form that shows the html, the boxes (chekbox) are not checked, they remain blank and what I want is for only those boxes to be checked that are supposed to be instantiated with the instance that the user send Keep in mind that the training day it saves is something like this: training_days=['MON','TUE'] etc.How could I achieve that?? thank you

What I want is for only those boxes to be checked that are supposed to be instantiated with the instance that the user sends.

Make your dias_entrenamiento a JSONField [Django-doc]:

def default_dias_entrenamiento():
    return ['MON', 'TUE']


class Rutina(models.Model):
    dias_entrenamiento = models.JSONField(default=default_dias_entrenamiento)
    # …

This allows us to save a list of items as a JSON blob, but also reconstruct it, which often tends to be the main problem to retrieve the item back.

Вернуться на верх