How to get the ID of selected objects from a ModelMultipleChoiceField in Django

Hi everyone,

I’m trying to get the data from the multiple choicefield, but when I do, the model returns plain text and I can’t filter it with my database because i need a use a function from user. Also thought if it wouldn’t be possible to make the name show up in the form but the value at cleaned be another unambiguous value that is not the name.Thats my view.py

def generar_solicitud_view(request):   
    form_editores = editores_form(request.POST)
    if request.method == 'POST':
        if form_editores.is_valid():
            editores= form_editores.cleaned_data['editores']
            informe = Informe.objects.create(Informe_Estado="Pendiente",Informe_Fecha_Subida=Now())
            empleados = Empleado.objects.all()
            for editor in editores:
                empleados.objects.filter(usuario__get_full_name=editor).first()
                print(editor)
                print(empleado)
                informe.Editores.add(empleado)
                informe.save()
        else:
            messages.error(request, 'Se deben seleccionar como maximo 5 editores')
        
    contexto={
              'form_editores': form_editores,
              }
    return render(request,"informes/generar_solicitud.html",contexto)

Thats my models

class Empleado(models.Model):
    usuario = models.OneToOneField(User, on_delete=models.CASCADE)
    Empleado_Legajo_Ecovina = models.IntegerField(unique=True, default=1)
    Empleado_Cuit = models.CharField(unique = True, max_length=20)
    Empleado_Domicilio = models.CharField(max_length=50,default="DESCONOCIDO")
    Empleado_Partido = models.CharField(max_length=50,default="DESCONOCIDO")
    Empleado_Provincia = models.CharField(max_length=50,default="DESCONOCIDO")
    Empleado_Telefono = models.CharField(max_length=50,default="DESCONOCIDO")
    Empleado_Fecha_Inicio = models.DateField(default="2022-01-01")
    Puesto_Id = models.ForeignKey(Puesto, on_delete=models.SET_NULL, null=True)
    
    def __str__(self):
        return self.usuario.get_full_name()


class Informe(models.Model):
    Informe_Id = models.AutoField(primary_key=True)
    Informe_Archivo = models.FileField(upload_to= "informes/", null= True)
    Informe_Tema = models.CharField(max_length=50,choices=[
            ("Legal", "Legal"),
            ("Financiero", "Financiero"),
            ("Gestion", "Gestion"),
            ("Otros", "Otros"),
        ],)
    Informe_Fecha_Subida = models.DateField(null= True)
    Informe_Estado = models.CharField(max_length = 50,choices=[
            ("Finalizado","Finalizado"),
            ("Rechazado","Rechazado"),
            ("Pendiente","Pendiente"),
    ])
    Editores = models.ManyToManyField(Empleado)

Thanks

Please also post your form.

Side note: You’re going to create less confusion for yourself and others if you adopt the Django coding conventions and make your field names consistently lower case.

1 Like

Two other things you should be aware of.

First, Django is designed to handle saving related objects by itself. You don’t need to iterate over the selections to save them. (See Creating forms from models | Django documentation | Django)

Second, don’t confuse what you see as a result of a print function with what data actually exists in the model. Print does not necessarily show you the data in a model. It shows the output of the model’s __str__ method, which can be written to return anything.

1 Like