YassVegas
YassVegas

Reputation: 171

Django - Enter a list of value

MY MODEL :

class Annonce(models.Model):
    created_at = models.DateTimeField(editable=False)
    modified_at = models.DateTimeField()
    title = models.CharField(max_length=24)
    domaines = models.ManyToManyField(Domaine, null=True,related_name="%(app_label)s_%(class)s_related")

My FORM :

class annonceForm(forms.ModelForm) :
    class Meta : 
        model = Annonce
        fields = ['title','domaines','presentation']
        widgets = {
            'domaines': forms.Select(attrs={'size': 1}),
            }

def __init__(self, *args, **kwargs):
    super(annonceForm, self).__init__(*args, **kwargs)
    self.fields['domaines'].required = False
    self.fields['domaines'].queryset = Domaine.objects.all().values_list("nom",flat=True)

When I want save one Annonce in my form annonceForm, I have this error message :

" Enter a list of values " below the Select of "domaines"

Upvotes: 1

Views: 3702

Answers (2)

Manoj N
Manoj N

Reputation: 38

The domaines being ManyToManyField, the form widget suitable for your needs will be the forms.SelectMultiple

category = forms.ModelMultipleChoiceField(
    queryset=ProductCategory.objects.filter(is_published=True),
    widget=forms.SelectMultiple(attrs={'multiple': ''}),) 

Upvotes: 1

djangonaut
djangonaut

Reputation: 7778

For a M2M relation you should be using a MultipleChoiceField in your form class respectively it's widget SelectMultiple:

https://docs.djangoproject.com/en/1.7/ref/forms/fields/#multiplechoicefield

Django expects a list of values or an empty list for the M2M relation domaines while your form is sending a single value. Think about how would a single-select field display more than one value of an existing Annonce, it can't.

Upvotes: 3

Related Questions