How to limit select widget of many to many field to only a single option per submit

If I have the following models:

class Publication(models.Model):
    title = models.CharField(max_length=30)

    class Meta:
        ordering = ["title"]

    def __str__(self):
        return self.title


class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    class Meta:
        ordering = ["headline"]

    def __str__(self):
        return self.headline

and the following form:

class ArticleForm(forms.ModelForm):
    
    class Meta:
        model = Article
        fields = ["headline", "publications"]

How can I limit the widget of “publications” so the user can select only 1 option? I think modifying clean_publications() would work but I want the template to only allow a single option aswell.

I think the easiest thing to do is to specify the form field for publications as a ModelChoiceField instead of allowing it to be the default ModelMultipleChoiceField.

1 Like