Django - How does the ModelChoiceField selection request work?

I have a form with ModelChoiceField, and I want to load a table from my database onto it. If I use this set of queries in my init form, then my view form.is_valid works fine:

self.fields['categoria_formfield'].queryset = sitio_categoria.objects.exclude(categoria='patrimonio').values_list('idCategoria',flat=True) 

enter image description here

This code shows a list of identifiers on ModelChoiceField, but I need it to show a list of categories. Therefore, I use:

 self.fields['categoria_formfield'].queryset = sitio_categoria.objects.exclude(categoria='patrimonio').values_list('categoria',flat=True) 

But using this code .is_valid does not check and I get a form error: "Choose the right one. This choice is not one of the available options." Some suggest what might be the problem?

Error recived

MODEL

 class sitio_categoria(models.Model): idCategoria = models.AutoField(primary_key=True) categoria = models.CharField(max_length=30, null=False, unique=True) 

THE FORM

 class anadirComercioPaso1_form(forms.Form): categoria_formfield = forms.ModelChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), queryset=sitio_categoria.objects.none()) def __init__(self, *args, **kwargs): super(anadirComercioPaso1_form, self).__init__(*args,**kwargs) self.fields['categoria_formfield'].queryset = sitio_categoria.objects.exclude(categoria='patrimonio').values_list('categoria',flat=True) 
+8
django validation forms dynamic-forms
source share
1 answer

Do not use values_list , (or values ), ModelChoiceField needs real model objects.

 queryset = sitio_categoria.objects.exclude(categoria='patrimonio') 

ModelChoiceField will use the primary keys of objects for validation and their Unicode representation for display. Therefore, you will need to define the conversion to unicode in your model:

 class sitio_categoria(models.Model): idCategoria = models.AutoField(primary_key=True) categoria = models.CharField(max_length=30, null=False, unique=True) def __unicode__(self): return self.categoria 

ModelChoiceField Documentation

The model method of the __unicode__ model will be called to create string representations of objects for use in selecting fields;

+13
source share

All Articles