djangodjango-forms

Enter a list of values error in forms when ManyToManyField rendered with different type of input


I changed the widget of my ManyToManyField, tags, in my model to hidden...

class PreachingForm(ModelForm):
    class Meta:
        model = Preaching
        fields = ['title', 'text', 'date', 'privacy', 'tags']   
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'tags': forms.HiddenInput(), #changed to hidden input
        }

... and in the html, I'm supplying the hidden input with comma separated values

<input type="hidden" name="tags" value="Tag1,Tag2" id="id_tags">

The problem is I'm getting a form error saying Enter a list of values and I want to strip(',') the data I got from the hidden input so it might be fixed but I have no idea how to do it.


Solution

  • My initial solution was to clean the tag field using

    def clean_tags:
        #code here
    

    but it was not working because the clean_tags is not even called in the first place.

    I tried to change my tags as charfield

    tags = forms.CharField(required = True, max_length=255, widget=forms.HiddenInput)
    

    and the clean method is now being called.

     def clean_tags(self):
            data = self.cleaned_data['tags']
            if data is None:
                raise 
            tags = tuple(Tag.objects.get_or_create(title=tag) for tag in tuple(data.split(',')))
            return tuple([x[0].id for x in list(tags) ])